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.
numbers = [1, 2, 3, 4]
result = all(num > 0 for num in numbers)
print(result) # True2. 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.
numbers = [1, 5, 8, 12]
result = any(num > 10 for num in numbers)
print(result) # True3. argparse – Command‑line argument parsing
The argparse module helps create user‑friendly command‑line interfaces, automatically generating help messages and handling type conversion.
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}!")4. collections.Counter – Counting hashable objects
Counteris a dict subclass for tallying occurrences of elements in an iterable.
from collections import Counter
text = "hello world"
counter = Counter(text)
print(counter) # Counter({'l': 3, 'o': 2, ...})5. collections.defaultdict – Dictionaries with default values
defaultdictautomatically creates a default value for missing keys, avoiding KeyError.
from collections import defaultdict
dd = defaultdict(int)
dd['a'] += 1
print(dd) # defaultdict(<class 'int'>, {'a': 1})6. dataclasses.dataclass – Lightweight data classes
The dataclass decorator generates __init__, __repr__, and comparison methods automatically.
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int = 25
person = Person(name="Bob")
print(person) # Person(name='Bob', age=25)7. datetime – Date and time handling
The datetime module provides classes for dates, times, and timedeltas, useful for timestamps, formatting, and arithmetic.
from datetime import datetime, timedelta
now = datetime.now()
future = now + timedelta(days=10)
print(f"Now: {now}, 10 days later: {future}")8. functools.lru_cache – Caching function results
The lru_cache decorator caches recent function calls to speed up repeated computations, especially recursive algorithms.
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))9. itertools.chain – Concatenating iterables
chainjoins multiple iterables into a single iterator without creating intermediate lists.
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]10. json – JSON serialization and deserialization
The json module converts between Python objects and JSON strings, supporting dump, load, dumps, and loads.
import json
data = {'name': 'John', 'age': 30}
json_str = json.dumps(data)
print(json_str)
obj = json.loads(json_str)
print(obj['name'])11. pickle – Object serialization
pickleserializes arbitrary Python objects to a byte stream and restores them, useful for persistence and inter‑process communication.
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)12. pprint – Pretty‑printing data structures
pprintformats nested containers for readable console output.
from pprint import pprint
data = {'name': 'Alice', 'details': {'age': 30, 'city': 'Wonderland'}}
pprint(data)13. re – Regular expressions
The re module provides pattern matching, searching, substitution, and splitting capabilities for text processing.
import re
email = '[email protected]'
if re.match(r'^\w+@[a-zA-Z_]+?\.\w{2,3}$', email):
print('Valid')
else:
print('Invalid')14. timeit.timeit – Measuring execution time
timeit.timeitaccurately times small code snippets, useful for performance analysis.
import timeit
exec_time = timeit.timeit('sum(range(100))', number=10000)
print(f"Execution time: {exec_time}s")15. uuid – Generating unique identifiers
The uuid module creates universally unique identifiers (UUIDs) of various versions.
import uuid
uid = uuid.uuid4()
print(uid)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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
