Standard Library Tour

স্ট্যান্ডার্ড লাইব্রেরি ট্যুর — "Batteries Included"

Read: ~30 min Intermediate 5 practice problems Live code runner

1. "Batteries Included"

Python ships with hundreds of modules covering practical problems — file paths, dates, HTTP, crypto, compression, XML, databases, math, random numbers, and a dozen specialized collections. Before installing a third-party package, always ask: is this already in the standard library? Usually the answer is yes.

Python-এর সঙ্গেই আসে শতাধিক module — ফাইল path, তারিখ, HTTP, crypto, compression, XML, database, math, random, ও বিশেষ collection। তৃতীয়-পক্ষের package install করার আগে নিজেকে জিজ্ঞাসা করুন: এটি কি ইতিমধ্যেই stdlib-এ আছে? বেশিরভাগ সময় উত্তর হ্যাঁ।

2. os, sys, pathlib

os_sys.py
import os, sys
from pathlib import Path

print("Python:", sys.version.split()[0])
print("Platform:", sys.platform)
print("CWD:", os.getcwd())

# pathlib preferred over os.path
home = Path.home()
print("Home:", home)
print("Parent of cwd:", Path.cwd().parent)
print("Arguments:", sys.argv)

3. datetime

datetime_demo.py
from datetime import datetime, date, timedelta

now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M"))

# Arithmetic with timedelta
tomorrow = date.today() + timedelta(days=1)
week_ago  = date.today() - timedelta(weeks=1)
print(tomorrow, week_ago)

# Parsing text
ev = datetime.strptime("2025-12-16 19:30", "%Y-%m-%d %H:%M")
print(ev.year, ev.month, ev.weekday())

4. collections — Specialized Containers

collections_demo.py
from collections import Counter, deque, defaultdict

# Counter — tally anything
votes = ["A", "B", "A", "C", "B", "A"]
c = Counter(votes)
print(c)
print(c.most_common(1))

# deque — fast appends/pops at both ends (O(1))
d = deque([1, 2, 3])
d.appendleft(0)
d.append(4)
print(d)
print(d.popleft(), d)

# defaultdict — factory for missing keys
groups = defaultdict(list)
for name in ["Asif", "Mou", "Akter", "Bashir"]:
    groups[name[0]].append(name)
print(dict(groups))

5. itertools — Combinatorial Building Blocks

itertools_demo.py
from itertools import chain, combinations, permutations, product, accumulate, count, islice

# chain — glue iterables
print(list(chain([1, 2], (3, 4), "ab")))

# combinations / permutations
print(list(combinations("ABC", 2)))
print(list(permutations("AB")))

# product — Cartesian
print(list(product([1, 2], ["x", "y"])))

# accumulate — running totals
print(list(accumulate([1, 2, 3, 4])))

# islice — bounded view of an infinite iterator
print(list(islice(count(100, 5), 5)))

6. functools — Tools for Functions

functools_demo.py
from functools import lru_cache, reduce, partial

# Memoization for free
@lru_cache(maxsize=None)
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(fib(50))

# reduce — fold a sequence
print(reduce(lambda a, b: a * b, [1, 2, 3, 4, 5]))

# partial — freeze some arguments
def greet(greeting, name):
    return f"{greeting}, {name}!"

hello = partial(greet, "Hello")
print(hello("Bangladesh"))

7. Vocabulary (শব্দভাণ্ডার)

TermMeaningবাংলায়
Standard libraryModules shipped with Python itself.Python-এর সাথেই আসা module-সমূহ।
CounterDict subclass that counts items.Item count করা dict।
dequeDouble-ended queue; fast on both ends.দুই দিক থেকে দ্রুত push/pop হওয়া queue।
MemoizationCache past results to avoid recomputation.পুরোনো ফলাফল cache করা।
Partial applicationCreating a new function by fixing args.কিছু argument fix করে নতুন ফাংশন বানানো।

8. Practice Problems

  1. Use Counter to find the 3 most common words in a sentence.
    Counter দিয়ে একটি বাক্যের সবচেয়ে বেশি ব্যবহৃত ৩টি শব্দ বের করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans1.py
    from collections import Counter
    text = "python is easy python is fun python rocks"
    print(Counter(text.split()).most_common(3))
  2. Use a deque to keep the last 5 elements of a growing list of 20 numbers.
    deque দিয়ে ২০টি সংখ্যার শেষ ৫টি রাখুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans2.py
    from collections import deque
    recent = deque(maxlen=5)
    for i in range(20):
        recent.append(i)
    print(list(recent))
  3. Compute days between 2025-01-01 and today using datetime.
    ২০২৫-০১-০১ থেকে আজ পর্যন্ত কত দিন — datetime দিয়ে বের করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans3.py
    from datetime import date
    diff = date.today() - date(2025, 1, 1)
    print(diff.days, "days")
  4. Use lru_cache to speed up a recursive function that counts ways to climb N stairs (1 or 2 steps).
    lru_cache দিয়ে একটি recursive stair-climbing ফাংশন দ্রুত করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans4.py
    from functools import lru_cache
    
    @lru_cache
    def ways(n):
        if n < 2:
            return 1
        return ways(n - 1) + ways(n - 2)
    
    print(ways(30))
  5. List every pair of students from ["A","B","C","D"] using itertools.combinations.
    itertools.combinations দিয়ে প্রত্যেক জোড়া শিক্ষার্থী list করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans5.py
    from itertools import combinations
    print(list(combinations(["A", "B", "C", "D"], 2)))

Summary — Module 25

The standard library is Python's secret weapon. Know collections (Counter, deque, defaultdict), itertools (chain, combinations, accumulate), and functools (lru_cache, reduce, partial). Prefer pathlib over os.path for paths; use datetime for time arithmetic. When you think "I need to write X", check the stdlib first.

stdlib হলো Python-এর গোপন অস্ত্র। collections, itertools, functools, pathlib, datetime — এগুলোতে দক্ষ হোন। কোড লেখার আগে stdlib-এ খুঁজুন — বেশির ভাগ সময় ইতিমধ্যে সমাধান আছে।

Next Module → Decorators & Context Managers।