Python comes with a large collection of modules that provide ready-to-use functionality for common programming tasks. These modules cover areas such as mathematics, file handling, dates, regular expressions, data formats, system operations and databases. Common applications include:
- Mathematical and statistical calculations
- File and directory management
- Working with JSON, CSV and databases
- System and command-line operations
- Text processing and pattern matching
How to Import Built-in Module
It can be imported using the import statement. No separate package installation is required for modules included with the Python distribution.
import math
print(math.sqrt(25))
Output
5.0
Explanation:
- math.sqrt(25) calculates the square root of 25.
- Result is printed as 5.0.
Finding Built-in Modules
Python's sys module provides sys.builtin_module_names for modules compiled into the current Python interpreter.
import sys
print(sys.builtin_module_names)
Output
('_abc', '_ast', '_codecs', '_collections', '_functools', '_imp', '_io', '_locale', '_operator', '_signal', '_sre', '_stat', '_string', '_suggestions', '_symtable', '_sysconfig', '_thread', '_tokenize...Explanation:
- sys.builtin_module_names returns a tuple containing modules compiled into the current interpreter.
- This list is different from the complete Standard Library module list.
Common Built-in and Standard Library Modules
1. JSON
json module is used to convert Python objects to JSON data and JSON data back to Python objects. It is commonly used for configuration files and data exchange between applications.
import json
data = {
"name": "Alice",
"age": 25,
"skills": ["Python", "SQL"]
}
result = json.dumps(data, indent=4)
print(result)
Output
{
"name": "Alice",
"age": 25,
"skills": [
"Python",
"SQL"
]
}
Explanation:
- json.dumps() serializes a Python object into a JSON string.
- indent=4 formats the resulting JSON for readability.
- json.loads() performs the reverse operation.
For more information, see Python JSON.
2. math Module
It provides mathematical functions and constants for operations such as square roots, logarithms, trigonometry and rounding.
import math
print(math.sqrt(64))
print(math.factorial(5))
print(math.pi)
Output
8.0 120 3.141592653589793
Explanation:
- math.sqrt() returns the square root.
- math.factorial() calculates a factorial.
- math.pi provides the value of π.
For more information, see Python Math Module.
3. random Module
This module generates pseudo-random values and provides functions for selecting, shuffling and sampling elements from sequences.
import random
random.seed(10)
print(random.randint(1, 10))
print(random.choice(["Python", "Java", "C++", "JavaScript"]))
Output
10 Python
Explanation:
- random.randint() generates a random integer within the specified range.
- random.choice() selects one item from a sequence.
- random.seed() makes the example reproducible.
For more information, see Python Random Module.
4. datetime Module
It provides classes for representing and manipulating dates, times and time intervals. It includes date, time, datetime and timedelta types.
from datetime import date, timedelta
today = date(2026, 9, 20)
future = today + timedelta(days=10)
print(today)
print(future)
Output
2026-09-20 2026-09-30
Explanation:
- date() creates a date object.
- timedelta() represents a time interval.
- Date objects can be added to or subtracted from using timedeltas.
For more information, see Python datetime Module.
5. os Module
os module provides a portable interface for interacting with operating-system functionality, including directories, environment variables and process-related information.
import os
print(os.getcwd())
print(os.environ.get("HOME"))
Output
/home/guest/sandbox/56167e9f-9191-4d34-ada2-0a7a375f3f2d /home/guest
Explanation:
- os.getcwd() returns the current working directory.
- os.environ provides access to environment variables.
- Output paths depend on the operating system and environment.
6. sys Module
This module provides access to Python interpreter and runtime information. It is commonly used for command-line arguments, module paths, input/output streams and interpreter settings.
import sys
print(sys.version_info.major)
print(sys.argv[0])
Output
3 Solution.py
Explanation:
- sys.version_info contains information about the Python version.
- sys.argv stores command-line arguments passed to a program.
- sys.argv[0] normally contains the script name.
7. re Module
It provides regular expression operations for searching, matching, splitting and replacing text based on patterns.
import re
text = "Python was released in 1991."
result = re.findall(r"\d+", text)
print(result)
Output
['1991']
Explanation:
- re.findall() finds all non-overlapping matches.
- Pattern \d+ matches one or more digits.
- Result is returned as a list.
For more information, see Python RegEx.
8. hashlib Module
It provides secure hash algorithms such as SHA-256 for creating message digests. It is useful for integrity checking and cryptographic applications.
import hashlib
message = "Hello"
result = hashlib.sha256(message.encode()).hexdigest()
print(result)
Output
185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969
Explanation:
- encode() converts the string into bytes.
- sha256() creates a SHA-256 hash object.
- hexdigest() returns the hash as a hexadecimal string.
For more information, see hashlib module in Python.
9. calendar Module
This module provides functions for calendar-related calculations and for generating calendar representations.
import calendar
print(calendar.month(2026, 9))
Output
September 2026
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30Explanation:
- calendar.month() generates a formatted calendar for a specific month.
- Function accepts a year and month as arguments.
For more information, see Python Calendar Module.
10. heapq Module
This module implements a heap-based priority queue using a regular Python list. Its main implementation is a min-heap.
import heapq
numbers = [5, 2, 8, 1, 3]
heapq.heapify(numbers)
print(numbers)
print(heapq.heappop(numbers))
print(numbers)
Output
[1, 2, 8, 5, 3] 1 [2, 3, 8, 5]
Explanation:
- heapify() rearranges the list into a min-heap.
- heappop() removes and returns the smallest element.
- Remaining list continues to satisfy the heap property.
11. collections Module
It provides specialized container types such as Counter, defaultdict, deque and namedtuple. These are useful when built-in containers are not sufficient for a particular task.
from collections import Counter
data = ["Python", "Java", "Python", "C++", "Java", "Python"]
count = Counter(data)
print(count)
print(count["Python"])
Output
Counter({'Python': 3, 'Java': 2, 'C++': 1})
3
Explanation:
- Counter counts how many times each element occurs.
- It behaves like a dictionary containing elements and their frequencies.
For more information, see Python Collections Module.
12. pathlib Module
pathlib module provides an object-oriented way to work with filesystem paths. It offers platform-independent operations for files and directories.
from pathlib import Path
path = Path("documents") / "notes.txt"
print(path)
print(path.suffix)
Output
documents/notes.txt .txt
Explanation:
- Path creates an object representing a filesystem path.
- The / operator joins path components.
- suffix returns the file extension.
For more information, see Pathlib Module in Python.
13. shutil Module
It provides high-level operations for copying, moving, renaming and deleting files and directories.
import shutil
shutil.copy("source.txt", "backup.txt")
print("File copied successfully")
Output
File copied successfully.
Explanation:
- shutil.copy() copies a file to another location.
- Destination file is created with the copied contents.
For more information, see Shutil Module in Python.
14. csv Module
It provides functionality for reading and writing comma-separated values files. It supports reader and writer objects for processing tabular data.
import csv
from io import StringIO
data = "Name,Age\nAlice,25\nBob,30"
reader = csv.DictReader(StringIO(data))
for row in reader:
print(row["Name"], row["Age"])
Output
Alice 25 Bob 30
Explanation:
- DictReader reads each CSV row as a dictionary.
- Column names become dictionary keys.
- StringIO allows the example to process CSV text without creating a physical file.
15. statistics Module
This module provides functions for calculating common statistics such as mean, median, mode and standard deviation. It is intended for general-purpose statistical calculations rather than advanced scientific computing.
import statistics
data = [10, 20, 20, 30, 40]
print(statistics.mean(data))
print(statistics.median(data))
print(statistics.mode(data))
Output
24 20 20
Explanation:
- mean() calculates the arithmetic average.
- median() returns the middle value.
- mode() returns the most frequently occurring value.
16. itertools Module
This module provides iterator-building functions designed to create efficient and memory-friendly iteration pipelines.
from itertools import combinations
items = ["A", "B", "C"]
result = list(combinations(items, 2))
print(result)
Output
[('A', 'B'), ('A', 'C'), ('B', 'C')]
Explanation:
- combinations() generates combinations of a specified length.
- Each combination is produced as a tuple.
- itertools functions generally produce iterators instead of creating all results immediately.
17. functool Module
It provides higher-order functions and utilities for working with callable objects. It includes tools such as partial(), cache() and lru_cache().
from functools import reduce
numbers = [1, 2, 3, 4]
result = reduce(lambda x, y: x + y, numbers)
print(result)
Output
10
Explanation:
- reduce() repeatedly applies a function to the elements of an iterable.
- Here, the values are combined to calculate their total.
For more information, see Functools module in Python.
18. subprocess Module
This module allows a Python program to start external processes and communicate with their input, output and error streams. subprocess.run() is the recommended interface for common use cases.
import subprocess
import sys
result = subprocess.run(
[sys.executable, "-c", "print('Hello from subprocess')"],
capture_output=True,
text=True
)
print(result.stdout.strip())
Output
Hello from subprocess
Explanation:
- subprocess.run() starts another process and waits for it to finish.
- capture_output=True captures its output.
- text=True returns the captured output as a string.
For more information, see Python subprocess module.
19. logging Module
It provides a standard system for recording application events. It supports different severity levels such as DEBUG, INFO, WARNING, ERROR and CRITICAL.
import logging
logging.basicConfig(
level=logging.INFO,
format="%(levelname)s: %(message)s"
)
logging.info("Program started")
logging.warning("Low memory")
Output
INFO: Program started
WARNING: Low memory
Explanation:
- basicConfig() sets the logging configuration.
- info() records informational messages.
- warning() records potentially problematic situations.
For more information, see Logging in Python.
20. argparse Module
This module provides tools for creating command-line interfaces. It supports command-line options, type conversion, default values and automatically generated help messages.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--name")
args = parser.parse_args(["--name", "Alice"])
print(args.name)
Output
Alice
Explanation:
- ArgumentParser() creates a command-line argument parser.
- add_argument() defines an expected option.
- parse_args() processes the provided arguments.
For more information, see Command Line Arguments in Python.
21. urlib Module
urllib package provides modules for working with URLs, including opening URLs and parsing URL components.
from urllib.parse import urlparse
url = "https://example.com/products?id=10"
result = urlparse(url)
print(result.scheme)
print(result.netloc)
print(result.path)
print(result.query)
Output
https example.com /products id=10
Explanation:
- urlparse() divides a URL into separate components.
- scheme identifies the protocol.
- netloc contains the domain.
- path and query contain the requested resource and parameters.
22. sqlite3 Module
It provides a DB-API 2.0 interface to SQLite databases. SQLite stores data in a lightweight database file and does not require a separate database server.
import sqlite3
connection = sqlite3.connect(":memory:")
cursor = connection.cursor()
cursor.execute("CREATE TABLE students (name TEXT, age INTEGER)")
cursor.execute("INSERT INTO students VALUES (?, ?)", ("Alice", 22))
cursor.execute("SELECT * FROM students")
print(cursor.fetchone())
connection.close()
Output
('Alice', 22)
Explanation:
- connect(":memory:") creates a temporary database in memory.
- execute() runs SQL statements.
- Parameter placeholders help pass values separately from the SQL statement.
- fetchone() retrieves one result row.
23. string Module
This module provides useful constants and utilities for working with text, including predefined character groups such as letters, digits and punctuation.
import string
print(string.ascii_letters)
print(string.digits)
Output
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789
Explanation:
- ascii_letters contains lowercase and uppercase ASCII letters.
- digits contains characters from 0 to 9.
- These constants are useful for validation and text-processing tasks.
For more information, see Python String Module.
24. time Module
This module provides functions for accessing system time, converting timestamps and pausing program execution.
import time
timestamp = time.time()
print(type(timestamp).__name__)
Output
float
Explanation:
- time.time() returns the current time as a floating-point value representing seconds since the epoch.
- time.sleep() can be used to pause program execution.
For more information, see Python Time Module.
25. tkinter Module
tkinter is Python's standard interface to the Tk GUI toolkit and can be used to build desktop applications with windows, buttons, labels and other widgets.
import tkinter as tk
root = tk.Tk()
root.title("Python GUI")
label = tk.Label(root, text="Hello, Python!")
label.pack()
root.mainloop()
Output
A GUI window titled "Python GUI" appears with the text "Hello, Python!".
Explanation:
- Tk() creates the main application window.
- Label() creates a text widget.
- mainloop() starts the GUI event loop.
26. builtins Module
It provides direct access to Python's built-in identifiers, such as functions and exceptions. It is usually used implicitly rather than imported directly in normal programs.
import builtins
print(builtins.len([10, 20, 30]))
print(builtins.max(4, 8, 2))
Output
3 8
Explanation:
- builtins.len() accesses Python's built-in len() function explicitly.
- builtins.max() accesses the built-in max() function.
- Most programs use these functions directly without importing builtins.
Built-in Modules vs External Modules
| Feature | Built-in / Standard Library | External Module |
|---|---|---|
| Installation | Usually included with Python | Usually installed separately |
| Source | Python distribution | Third-party developer or project |
| Example | math, os, json, pathlib | NumPy, Pandas, Requests |
| Package manager required | Usually no | Usually yes |
| Availability | Depends on Python distribution/version | Depends on installation |