C
PY

C to Python

10 lessons

Progress0%
1Variables & Types2Functions3Arrays → Lists4Structs → Classes & Dicts5Memory Management6String Handling7File I/O8Object-Oriented Programming9Exceptions and Context Managers10Standard Library and Tools
All Mirror Courses
C
PY
Standard Library and Tools
MirrorLesson 10 of 10
Lesson 10

Standard Library and Tools

Python's batteries-included stdlib vs C's minimal standard library

Introduction

In this lesson, you'll learn about standard library and tools in Python. Coming from C, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.

Mirror Card
C
From C:

In C, you're familiar with python's batteries-included stdlib vs c's minimal standard library.

PY
In Python:

Python has its own approach to python's batteries-included stdlib vs c's minimal standard library, which we'll explore step by step.

The Python Way

Let's see how Python handles this concept. Here's a typical example:

PY
Python Example
import re, json, datetime, collections, itertools, functools
from pathlib import Path

# String: rich built-ins
s = "Hello World"
s.upper(); s.lower(); s.split(); s.strip()
", ".join(["a","b","c"])
s.replace("World","Python")

# Regex (no C equivalent without POSIX)
import re
m = re.search(r"\d+", "abc123")
m.group()  # "123"
re.findall(r"\w+", "hello world")  # ["hello","world"]

# JSON (huge improvement over C's manual parsing)
import json
obj = json.loads('{"name":"Alice","age":30}')
json.dumps(obj, indent=2)

# Date/time
from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)
now.strftime("%Y-%m-%d")

# Collections
from collections import Counter, defaultdict, deque
Counter(["a","b","a","c","b","a"]) # {"a":3,"b":2,"c":1}
d = defaultdict(list)
d["key"].append(1)  # no KeyError

# Sorting
data = [3,1,4,1,5]
sorted(data)                           # ascending
sorted(data, reverse=True)             # descending
sorted(people, key=lambda p: p.age)    # by field

Comparing to C

Here's how you might have written similar code in C:

C
C (What you know)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>

// String: manual operations
char buf[100];
strcpy(buf, "Hello");
strcat(buf, " World");
strlen(buf);
toupper(buf[0]);

// Math
sqrt(2.0); pow(2, 10); fabs(-3.14);

// Random (not cryptographically safe)
srand(time(NULL));
int r = rand() % 100;  // 0-99

// Time
time_t now = time(NULL);
struct tm *tm = localtime(&now);
printf("%d-%02d-%02d\n", tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday);

// Sort
int arr[] = {3,1,4,1,5};
int cmp(const void *a, const void *b) { return *(int*)a - *(int*)b; }
qsort(arr, 5, sizeof(int), cmp);
Mirror Card
C
From C:

You may be used to different syntax or behavior.

PY
In Python:

Python's stdlib has 200+ modules; C's stdlib has ~30 headers — much more batteries-included

Mirror Card
C
From C:

You may be used to different syntax or behavior.

PY
In Python:

re module for regex (no POSIX needed); json module for easy JSON parsing

Mirror Card
C
From C:

You may be used to different syntax or behavior.

PY
In Python:

datetime module with arithmetic; C needs manual tm struct calculations

Mirror Card
C
From C:

You may be used to different syntax or behavior.

PY
In Python:

sorted() is a built-in; C needs qsort() with a comparison function

Mirror Card
C
From C:

You may be used to different syntax or behavior.

PY
In Python:

collections.Counter, defaultdict, deque have no C stdlib equivalents

Step-by-Step Breakdown

1. String Operations

Python strings are objects with methods. No manual buffer management, no strcpy/strcat. String formatting with f-strings replaces sprintf.

C
C
char buf[200];
strcpy(buf, "Hello ");
strcat(buf, name);
printf("%s\n", buf);
PY
Python
greeting = "Hello " + name
greeting = f"Hello {name}"  # f-string (safer)
print(greeting)

2. Collections

Python's collections module has specialized data structures. Counter auto-counts, defaultdict avoids KeyError, deque is O(1) on both ends.

C
C
// C: manual hash table or sorted array for counting
PY
Python
from collections import Counter, defaultdict
words = "hello world hello python".split()
Counter(words)          # {"hello":2,"world":1,"python":1}
graph = defaultdict(list)
graph["a"].append("b")  # no need to check if key exists

3. JSON and Data

Python's json module serializes/deserializes automatically. C has no stdlib JSON support — requires third-party libraries.

C
C
// C: no stdlib JSON — use cJSON or jansson library
PY
Python
import json
data = json.loads(text)       # text → dict
json.dumps(data, indent=2)    # dict → text

# With file:
with open("data.json") as f:
    obj = json.load(f)

4. Dates and Times

Python's datetime is much easier than C's time_t + struct tm. Arithmetic works with timedelta.

C
C
time_t now = time(NULL);
struct tm *t = localtime(&now);
printf("%d-%02d-%02d", t->tm_year+1900, t->tm_mon+1, t->tm_mday);
PY
Python
from datetime import datetime, timedelta
now = datetime.now()
print(now.strftime("%Y-%m-%d"))
tomorrow = now + timedelta(days=1)
diff = datetime(2026,1,1) - now
print(f"{diff.days} days until 2026")

Common Mistakes

When coming from C, developers often make these mistakes:

  • Python's stdlib has 200+ modules; C's stdlib has ~30 headers — much more batteries-included
  • re module for regex (no POSIX needed); json module for easy JSON parsing
  • datetime module with arithmetic; C needs manual tm struct calculations
Common Pitfall
Don't assume Python works exactly like C. While the concepts may be similar, the syntax and behavior can differ significantly.

Key Takeaways

  • Python stdlib: re (regex), json, datetime, pathlib, os, collections — 200+ modules
  • collections.Counter/defaultdict/deque solve common patterns without C-style workarounds
  • json.loads/dumps for easy JSON — no third-party library needed
  • datetime with timedelta arithmetic replaces C's manual tm struct calculations
Rule of Thumb
The best way to learn is by doing. Try rewriting some of your C code in Python to practice these concepts.
PreviousFinish