The Python Standard Library is a collection of modules included with Python that provides a wide range of functionalities such as file handling, networking, cryptography, regular expressions, data manipulation, and more. These modules allow developers to perform various tasks without needing external dependencies.

Python's standard library is extensive and well-documented, making it one of the reasons Python is widely used for software development, scripting, automation, and data analysis.


Complete List of Python Standard Library Modules

Python provides an extensive Standard Library, which consists of built-in modules for performing various tasks such as file I/O, networking, data processing, and more.


Built-in Functions (No Import Needed)

  • print(), len(), type(), range(), input(), open()
  • sum(), min(), max(), sorted(), zip()
  • map(), filter(), reduce(), any(), all()
  • int(), float(), str(), list(), dict(), set(), tuple()
  • isinstance(), issubclass(), hasattr(), getattr(), setattr()

OS & System Interaction

  • os Operating system interfaces
  • sys System-specific parameters and functions
  • platform Information about the OS
  • shutil High-level file operations
  • subprocess Run and interact with system commands
  • signal Handling system signals
  • psutil (external) Process and system monitoring

File and Directory Handling

  • pathlib Object-oriented filesystem paths
  • os.path Functions for working with file paths
  • shutil File operations such as copying and moving
  • glob File pattern matching
  • fnmatch Unix filename pattern matching
  • tempfile Temporary file and directory handling
  • fileinput Read multiple input streams
  • linecache Efficient line-by-line file reading

Data Types and Collections

  • collections Specialized data structures (Counter, deque, etc.)
  • dataclasses Lightweight data classes
  • heapq Heap queue algorithm
  • bisect Array bisection algorithms
  • array Efficient numeric arrays
  • queue Queue implementation (FIFO, LIFO, PriorityQueue)
  • struct Binary data packing/unpacking

Math & Numeric Computations

  • math Mathematical functions
  • cmath Complex number math
  • decimal Floating-point arithmetic with precision
  • fractions Rational number calculations
  • random Random number generation
  • statistics Statistical calculations (mean, median, stdev)

Date & Time Handling

  • datetime Date and time manipulation
  • time Time functions (sleep, time)
  • calendar Calendar-related functions
  • zoneinfo Time zone support

Regular Expressions & String Processing

  • re Regular expressions
  • string String utility functions
  • textwrap Formatting and wrapping text
  • difflib Compare sequences (like diff)

Cryptography & Hashing

  • hashlib Secure hash functions (SHA, MD5, etc.)
  • hmac Hash-based message authentication
  • secrets Generate secure random numbers for cryptography

Data Serialization & File Formats

  • json JSON encoding and decoding
  • csv Read and write CSV files
  • pickle Serialize/deserialize Python objects
  • marshal Internal serialization format
  • sqlite3 SQLite database interface

Internet & Networking

  • socket Low-level networking
  • http.client HTTP protocol client
  • urllib URL handling and requests
  • ftplib FTP protocol
  • smtplib Send emails via SMTP
  • imaplib IMAP email client
  • poplib POP3 email client
  • ssl Secure socket layer encryption
  • requests (external) HTTP requests (popular alternative)

Web Services & Data Handling

  • html.parser Parse HTML documents
  • xml.etree.ElementTree Parse and create XML
  • xml.dom XML document object model
  • cgi Common Gateway Interface (CGI) support
  • json JSON handling

Multithreading & Concurrency

  • threading Multithreading support
  • multiprocessing Multi-process parallelism
  • asyncio Asynchronous programming
  • concurrent.futures High-level concurrent execution

Debugging, Profiling & Logging

  • logging Logging framework
  • traceback Extract, format, and print error traces
  • pdb Python debugger
  • timeit Measure execution time of small code snippets
  • profile Performance profiling

Testing & Code Quality

  • unittest Unit testing framework
  • doctest Test examples in docstrings
  • mock Mock objects for testing
  • pytest (external) Popular alternative for testing

GUI Programming

  • tkinter Standard Python interface to Tk GUI toolkit
  • PyQt (external) Python bindings for Qt
  • wxPython (external) wxWidgets toolkit

Compression & File Formats

  • zlib Compression using gzip format
  • gzip Read/write gzip files
  • bz2 Read/write bzip2 files
  • zipfile Create and extract ZIP archives
  • tarfile Create and extract TAR archives

Internationalization (i18n) & Localization

  • gettext Internationalization support
  • locale Localization support

Security & Access Control

  • crypt Password hashing
  • secrets Generate cryptographic secure tokens

Miscellaneous Utilities

  • enum Enumeration support
  • typing Type hints and annotations
  • dataclasses Create lightweight data classes
  • weakref Weak references to objects

Example: Working with Files and Directories

import os

# Get the current working directory
cwd = os.getcwd()
print("Current Working Directory:", cwd)

# List files in the directory
files = os.listdir(".")
print("Files in directory:", files)

# Create a new directory
os.mkdir("new_directory")

# Remove a directory
os.rmdir("new_directory")

Example: Command-line Arguments

import sys

# Print command-line arguments
print("Arguments passed:", sys.argv)

# Get the Python version
print("Python Version:", sys.version)

# Exit the script
sys.exit(0)

Example: Performing Mathematical Operations

import math

# Square root
print("Square root of 16:", math.sqrt(16))

# Logarithm
print("Logarithm of 100 (base 10):", math.log10(100))

# Trigonometry
print("Sine of 90 degrees:", math.sin(math.radians(90)))

Example: Generating Random Numbers

import random

# Generate a random integer between 1 and 10
print("Random integer:", random.randint(1, 10))

# Generate a random floating-point number between 0 and 1
print("Random float:", random.random())

# Shuffle a list
items = [1, 2, 3, 4, 5]
random.shuffle(items)
print("Shuffled list:", items)

Example: Getting and Formatting Date and Time

from datetime import datetime, timedelta

# Current date and time
now = datetime.now()
print("Current datetime:", now)

# Formatting date and time
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted datetime:", formatted)

# Adding 5 days to current date
future_date = now + timedelta(days=5)
print("Future date:", future_date)

Example: Searching for a Pattern

import re

text = "My email is example@mail.com"

# Search for an email pattern
pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
match = re.search(pattern, text)

if match:
    print("Found email:", match.group())

Example: Parsing and Creating JSON

import json

# Dictionary to JSON string
data = {"name": "Alice", "age": 25, "city": "New York"}
json_str = json.dumps(data)
print("JSON String:", json_str)

# JSON string to Dictionary
parsed_data = json.loads(json_str)
print("Parsed Data:", parsed_data)

Example: Reading and Writing CSV Files

import csv

# Writing to a CSV file
with open("data.csv", mode="w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age", "City"])
    writer.writerow(["Alice", 25, "New York"])
    writer.writerow(["Bob", 30, "Los Angeles"])

# Reading from a CSV file
with open("data.csv", mode="r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

Example: Using Counter

from collections import Counter

data = ["apple", "banana", "apple", "orange", "banana", "apple"]
counter = Counter(data)
print("Item counts:", counter)

Example: Using permutations

from itertools import permutations

items = [1, 2, 3]
perms = list(permutations(items))
print("Permutations:", perms)

Example: Using reduce

from functools import reduce

nums = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, nums)
print("Product of numbers:", product)

Example: Running a Function in a Thread

import threading

def print_numbers():
    for i in range(5):
        print(i)

# Create a thread
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()

Example: Creating a Simple Server

import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("localhost", 12345))
server.listen(5)
print("Server listening on port 12345")

Example: Logging Messages

import logging

logging.basicConfig(level=logging.INFO)
logging.info("This is an info message")
logging.warning("This is a warning")