Python's built-in libraries

Built-in libraries are modules that come with Python and are available right after installation, no pip install needed. They cover the most common tasks: maths, dates, JSON, the file system, random numbers, and a lot more.

What are built-in libraries?

Built-in libraries (the standard library) are a set of modules included in the Python distribution that you can use without any additional installation.

The main built-in libraries

Let's look at several of the most useful built-in libraries.

math: mathematical functions

The math module provides access to mathematical functions defined in the C language standard:

Python 3.13
import math

# Constants
print(f"Number π: {math.pi}")
Number π: 3.141592653589793
print(f"Number e: {math.e}")
Number e: 2.718281828459045
# Trigonometric functions
angle = math.pi / 4  # 45 degrees in radians
print(f"Sine of 45°: {math.sin(angle):.4f}")
Sine of 45°: 0.7071
print(f"Cosine of 45°: {math.cos(angle):.4f}")
Cosine of 45°: 0.7071
# Other functions
print(f"Factorial of 5: {math.factorial(5)}")
Factorial of 5: 120
print(f"Greatest common divisor of 12 and 18: {math.gcd(12, 18)}")
Greatest common divisor of 12 and 18: 6

random: generating random numbers

The random module provides functions for generating random numbers and picking random elements:

Python 3.13
import random

# Generating a random integer in a range
print(f"Random number between 1 and 10: {random.randint(1, 10)}")
Random number between 1 and 10: 7
# Random float between 0 and 1
print(f"Random number between 0 and 1: {random.random():.4f}")
Random number between 0 and 1: 0.3528
# Picking a random element from a sequence
fruits = ["apple", "banana", "orange", "pear"]
print(f"Random fruit: {random.choice(fruits)}")
Random fruit: orange
# Shuffling a sequence
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(f"Shuffled numbers: {numbers}")
Shuffled numbers: [3, 1, 5, 2, 4]

datetime: working with dates and times

The datetime module provides classes for working with dates and times:

Python 3.13
import datetime

# Current date and time
now = datetime.datetime.now()
print(f"Current date and time: {now}")
Current date and time: 2023-07-15 15:42:23.123456
# Creating a specific date
specific_date = datetime.date(2023, 12, 31)
print(f"Specific date: {specific_date}")
Specific date: 2023-12-31
# Difference between dates
today = datetime.date.today()
new_year = datetime.date(today.year + 1, 1, 1)
days_until_new_year = (new_year - today).days
print(f"Days until New Year: {days_until_new_year}")
Days until New Year: 170
# Formatting a date
formatted_date = now.strftime("%d.%m.%Y %H:%M")
print(f"Formatted date: {formatted_date}")
Formatted date: 15.07.2023 15:42

os: interacting with the operating system

The os module provides functions for interacting with the operating system:

Python 3.13
import os

# Getting the current working directory
print(f"Current directory: {os.getcwd()}")
Current directory: /Users/username/projects
# Listing files and folders in a directory
files = os.listdir('.')
print(f"First 3 files in the current directory: {files[:3]}")
First 3 files in the current directory: ['file1.txt', 'folder1', 'file2.py']
# System information
print(f"Operating system name: {os.name}")
Operating system name: posix
# Whether a file or directory exists
file_exists = os.path.exists('example.txt')
print(f"Does example.txt exist: {file_exists}")
Does example.txt exist: False

json: working with the JSON format

The json module provides functions for working with data in JSON format:

Python 3.13
import json

# A Python dictionary
person = {
    "name": "John",
    "age": 30,
    "city": "New York",
    "languages": ["Python", "JavaScript", "SQL"]
}

# Converting the dictionary to a JSON string
person_json = json.dumps(person, indent=4)
print("JSON string:")
print(person_json)
JSON string:
{
    "name": "John",
    "age": 30,
    "city": "New York",
    "languages": [
        "Python",
        "JavaScript",
        "SQL"
    ]
}
# Converting a JSON string back to a Python object
json_string = '{"name": "Mary", "age": 25, "city": "Boston"}'
person_dict = json.loads(json_string)
print(f"Name: {person_dict['name']}, Age: {person_dict['age']}")
Name: Mary, Age: 25

collections: specialised data types

The collections module provides several convenient data structures on top of the built-in ones. One of the most useful is Counter for counting elements:

Python 3.13
from collections import Counter

text = "Programming in Python is interesting and fun"
character_count = Counter(text.lower())

print("Three most common characters:")
for char, count in character_count.most_common(3):
    print(f"'{char}': {count}")
Three most common characters:
' ': 6
'n': 6
'i': 4

The module also has defaultdict, namedtuple, deque and others, advanced tools that will come in handy later.

Understanding check

Let's check how well you've understood the topic of built-in libraries:

Which library is best suited for working with dates in Python?


In the next lesson we'll look at third-party libraries, the ones installed via pip install that extend Python beyond the standard distribution.