Libraries in Python
Libraries in Python are collections of pre-written code that programmers can use to perform common tasks without writing code from scratch.
They help save time, improve efficiency, and allow developers to focus on solving problems rather than reinventing the wheel.
What is a Library?
A library in Python is a collection of modules that provides functions, classes, and variables which can be used to perform specific tasks.
- Modules → single files containing Python code
- Libraries → collection of multiple modules
1. Using a Built-in Library
Python comes with many built-in libraries, such as
math, random, and datetime.
Example
import math
print(math.sqrt(25))
print(math.factorial(5))
Explanation
import mathloads the built-in math library.sqrt(25)calculates the square root of 25 → output:5.0.factorial(5)calculates 5! → output:120.- No need to write our own square root or factorial functions.
2. Using an External Library
External libraries are created by others and can be installed using
pip.
Example
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr)
Explanation
numpyis an external library used for numerical operations.np.array([1, 2, 3, 4])creates an array from a Python list.- External libraries are installed using
pip install numpy.
3. Advantages of Using Libraries
- Reusability – No need to rewrite code
- Efficiency – Save time by using pre-written functions
- Reliability – Most libraries are tested and widely used
Example
numbers = [5, 2, 9, 1]
numbers.sort()
print(numbers)
Explanation
sort()is a built-in method from Python’s standard library.- The list is sorted in ascending order →
[1, 2, 5, 9]. - Saves effort and reduces chances of errors.