Essential Python Built-in Functions and Standard Library Modules with Examples
This article introduces essential Python built‑in functions and standard library modules such as all, any, argparse, collections, dataclasses, datetime, functools.lru_cache, itertools.chain, json, pickle, pprint, re, timeit, and uuid, providing concise explanations and practical code examples for each.
This article provides a comprehensive overview of many useful Python built‑in functions and standard library modules, explaining their purpose and showing practical usage examples.
1. all – Check if all elements satisfy a condition
The all function returns True when every element of an iterable meets a given condition, otherwise False . If the iterable is empty, it returns True .
<code>numbers = [1, 2, 3, 4]
result = all(num > 0 for num in numbers)
print(result) # True</code>2. any – Check if any element satisfies a condition
The any function returns True if at least one element of an iterable is true; otherwise it returns False . An empty iterable yields False .
<code>numbers = [1, 5, 8, 12]
result = any(num > 10 for num in numbers)
print(result) # True</code>3. argparse – Command‑line argument parsing
The argparse module helps create user‑friendly command‑line interfaces, automatically generating help messages and handling type conversion.
<code>import argparse
parser = argparse.ArgumentParser(description="Demo script")
parser.add_argument('--name', type=str, help='Your name')
args = parser.parse_args()
print(f"Hello, {args.name}!")</code>4. collections.Counter – Counting hashable objects
Counter is a dict subclass for tallying occurrences of elements in an iterable.
<code>from collections import Counter
text = "hello world"
counter = Counter(text)
print(counter) # Counter({'l': 3, 'o': 2, ...})</code>5. collections.defaultdict – Dictionaries with default values
defaultdict automatically creates a default value for missing keys, avoiding KeyError .
<code>from collections import defaultdict
dd = defaultdict(int)
dd['a'] += 1
print(dd) # defaultdict(<class 'int'>, {'a': 1})</code>6. dataclasses.dataclass – Lightweight data classes
The dataclass decorator generates __init__ , __repr__ , and comparison methods automatically.
<code>from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int = 25
person = Person(name="Bob")
print(person) # Person(name='Bob', age=25)</code>7. datetime – Date and time handling
The datetime module provides classes for dates, times, and timedeltas, useful for timestamps, formatting, and arithmetic.
<code>from datetime import datetime, timedelta
now = datetime.now()
future = now + timedelta(days=10)
print(f"Now: {now}, 10 days later: {future}")</code>8. functools.lru_cache – Caching function results
The lru_cache decorator caches recent function calls to speed up repeated computations, especially recursive algorithms.
<code>from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(100))</code>9. itertools.chain – Concatenating iterables
chain joins multiple iterables into a single iterator without creating intermediate lists.
<code>from itertools import chain
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = list(chain(list1, list2))
print(result) # [1, 2, 3, 4, 5, 6]</code>10. json – JSON serialization and deserialization
The json module converts between Python objects and JSON strings, supporting dump , load , dumps , and loads .
<code>import json
data = {'name': 'John', 'age': 30}
json_str = json.dumps(data)
print(json_str)
obj = json.loads(json_str)
print(obj['name'])</code>11. pickle – Object serialization
pickle serializes arbitrary Python objects to a byte stream and restores them, useful for persistence and inter‑process communication.
<code>import pickle
data = {'key': 'value'}
with open('data.pkl', 'wb') as f:
pickle.dump(data, f)
with open('data.pkl', 'rb') as f:
loaded = pickle.load(f)
print(loaded)</code>12. pprint – Pretty‑printing data structures
pprint formats nested containers for readable console output.
<code>from pprint import pprint
data = {'name': 'Alice', 'details': {'age': 30, 'city': 'Wonderland'}}
pprint(data)</code>13. re – Regular expressions
The re module provides pattern matching, searching, substitution, and splitting capabilities for text processing.
<code>import re
email = '[email protected]'
if re.match(r'^\w+@[a-zA-Z_]+?\.\w{2,3}$', email):
print('Valid')
else:
print('Invalid')</code>14. timeit.timeit – Measuring execution time
timeit.timeit accurately times small code snippets, useful for performance analysis.
<code>import timeit
exec_time = timeit.timeit('sum(range(100))', number=10000)
print(f"Execution time: {exec_time}s")</code>15. uuid – Generating unique identifiers
The uuid module creates universally unique identifiers (UUIDs) of various versions.
<code>import uuid
uid = uuid.uuid4()
print(uid)</code>Overall, the article serves as a quick reference guide for Python developers, covering common built‑in functions and modules with clear explanations and ready‑to‑run code snippets.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.