Modules & Built-in Functions¶
Python comes with a huge standard library of pre-written modules — and dozens of built-in functions that you can use without importing anything.
Built-in functions you'll use every day¶
nums = [3, 1, 4, 1, 5, 9, 2, 6]
print(len(nums)) # 8
print(sum(nums)) # 31
print(min(nums)) # 1
print(max(nums)) # 9
print(sorted(nums)) # [1, 1, 2, 3, 4, 5, 6, 9]
print(list(reversed(nums))) # reversed
print(abs(-10)) # 10
print(round(3.7)) # 4
print(pow(2, 10)) # 1024 — same as 2 ** 10
type(), isinstance() — check types:
print(type(5)) # <class 'int'>
print(type(5.0)) # <class 'float'>
print(isinstance(5, int)) # True
print(isinstance(5, (int, float))) # True — accepts a tuple of types
enumerate(), zip() — already used in Loops:
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
print(i, fruit)
prices = [50, 30, 80]
for fruit, price in zip(fruits, prices):
print(f"{fruit}: ₹{price}")
any(), all() — combine boolean checks:
nums = [2, 4, 6, 8, 9]
print(all(x > 0 for x in nums)) # True — every one positive
print(all(x % 2 == 0 for x in nums)) # False — 9 is odd
print(any(x > 5 for x in nums)) # True — 6, 8, 9 are > 5
map(), filter(), reduce() — see Functions.
input(), print(), int(), str(), float(), bool() — already covered.
Importing modules¶
A module is a .py file (or a folder of them) with reusable code.
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
print(math.factorial(5)) # 120
print(math.floor(3.7)) # 3
print(math.ceil(3.2)) # 4
print(math.log(100, 10)) # 2.0
Other import styles:
# Import specific names
from math import pi, sqrt
print(pi, sqrt(25))
# Rename on import
import math as m
print(m.pi)
# Import everything (avoid in real code — pollutes the namespace)
# from math import *
The most useful standard-library modules¶
random — random numbers¶
import random
print(random.random()) # float in [0.0, 1.0)
print(random.randint(1, 10)) # int in [1, 10] inclusive
print(random.uniform(0, 100)) # float in range
print(random.choice(["red", "green", "blue"])) # pick one
print(random.sample(range(100), 5)) # 5 unique picks
deck = list(range(1, 11))
random.shuffle(deck) # in-place shuffle
print(deck)
datetime — dates and times¶
from datetime import datetime, date, timedelta
now = datetime.now()
print("Now:", now)
print("Today:", date.today())
# Formatting
print(now.strftime("%Y-%m-%d %H:%M:%S"))
print(now.strftime("%A, %d %B %Y")) # full names
# Parsing
parsed = datetime.strptime("2025-01-31 14:30", "%Y-%m-%d %H:%M")
print(parsed)
# Arithmetic with timedelta
future = now + timedelta(days=7, hours=3)
print("Next week:", future)
diff = future - now
print("Difference:", diff)
os and pathlib — work with files and paths¶
import os
from pathlib import Path
# Current working directory
print(os.getcwd())
# List a folder
print(os.listdir("."))
# pathlib is the modern way
p = Path("./README.md")
print(p.name) # 'README.md'
print(p.suffix) # '.md'
print(p.stem) # 'README'
print(p.exists())
json — JSON encode/decode¶
import json
# Python → JSON string
data = {"name": "Alice", "age": 25, "skills": ["Python", "ML"]}
json_str = json.dumps(data, indent=2)
print(json_str)
# JSON string → Python
text = '{"city": "Mumbai", "pin": 400001}'
obj = json.loads(text)
print(obj["city"], obj["pin"])
re — regular expressions¶
import re
text = "Call me at 555-1234 or 555-5678"
# Find all phone-number-like patterns
phones = re.findall(r"\d{3}-\d{4}", text)
print(phones)
# Replace
clean = re.sub(r"\d{3}-\d{4}", "XXX-XXXX", text)
print(clean)
# Match start of string
m = re.match(r"(\w+) (\w+)", "Hello World")
if m:
print(m.group(1), m.group(2))
Common regex elements:
| Pattern | Matches |
|---|---|
\d |
digit (0-9) |
\w |
word character (letters, digits, _) |
\s |
whitespace |
. |
any character (except newline) |
* |
0 or more |
+ |
1 or more |
? |
0 or 1 |
{n} |
exactly n |
[abc] |
a, b, or c |
^ |
start of string |
$ |
end of string |
collections — specialized containers¶
from collections import Counter, defaultdict, deque, namedtuple
# Counter — counting things
print(Counter("mississippi")) # {'i': 4, 's': 4, 'p': 2, 'm': 1}
# defaultdict — auto-create missing keys
dd = defaultdict(list)
dd["fruits"].append("apple") # no need to initialize the list
dd["fruits"].append("banana")
print(dict(dd))
# deque — fast append/pop on both ends
dq = deque([1, 2, 3])
dq.appendleft(0)
dq.append(4)
print(dq)
# namedtuple — readable tuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y)
itertools — efficient looping¶
from itertools import product, combinations, permutations, chain
# All pairs from two lists
print(list(product([1, 2], ['a', 'b']))) # [(1,'a'), (1,'b'), (2,'a'), (2,'b')]
# Pick 2 from 4 (order doesn't matter)
print(list(combinations(['A', 'B', 'C', 'D'], 2)))
# Order matters
print(list(permutations(['A', 'B', 'C'], 2)))
# Flatten lists
print(list(chain([1, 2], [3, 4], [5, 6])))
Writing your own module¶
Create a file mymath.py:
Use it from another file in the same folder:
Installing third-party packages¶
Then in your code:
Practice¶
Print pi with 4-decimal precision
Expected: 3.1416
Quiz — Quick check¶
What you remember
Q1. Which import style is least recommended in production code?
-
import math -
from math import sqrt -
import math as m -
from math import *
Why:
from module import *pulls every name into your namespace and can silently shadow your own variables. Be explicit about what you import.
Q2. Which module would you use to read/write JSON?
-
csv -
pickle -
json -
xml
Why:
json.dumps(obj)converts Python → JSON string;json.loads(s)converts JSON → Python.pickleis for Python-only binary serialization (don't use it for external data).
Q3. What's the difference between random.randint(1, 10) and random.randrange(1, 10)?
- No difference
-
randintis inclusive of 10;randrangeis exclusive of 10 (gives 1–9) -
randintreturns a float;randrangereturns an int -
randrangeis deprecated
Why:
randint(a, b)mirrors common math notation (both ends included).randrange(a, b)follows Python'srange()convention (stop is exclusive).
Common doubts¶
What's the difference between a module and a package?
A module is a single .py file. A package is a folder of modules with an __init__.py file. You import both the same way — import mypackage.utils reaches into a folder.
Why use pathlib over os.path?
pathlib (Python 3.4+) is the modern, object-oriented way to work with paths. p = Path("data") / "file.csv" is clearer than os.path.join("data", "file.csv"). Methods like .exists(), .read_text(), .glob() live on the Path object directly. Use os only when you need OS-level functions that pathlib doesn't expose.
Where do pip install packages go?
Globally by default — installed into your Python's site-packages folder, shared across every project. That's a problem when projects need different versions of a library. The fix is a virtual environment: python -m venv .venv && source .venv/bin/activate. Now pip install only affects this project. Use one per project.