techmore.in

Python - Libraries

What Are Python Libraries?

Python libraries are collections of pre-written code that provide specific functionality. They help developers avoid reinventing the wheel by offering reusable modules and packages.

Why Use Python Libraries?

  • Speed up development
  • Ensure code reliability
  • Leverage community-tested tools

How to Use a Library?

You typically install third-party libraries using pip and import them in your scripts using import.

python
import math
print(math.sqrt(16))  # Outputs: 4.0

Built-in Libraries

Python includes many libraries out of the box:

  • math – Mathematical operations
  • datetime – Date and time manipulation
  • os – Interacting with the operating system
  • sys – System-specific parameters and functions

Popular Third-party Libraries

  • NumPy – Numerical computing
  • Pandas – Data manipulation and analysis
  • Matplotlib – Data visualization
  • Requests – HTTP requests
  • Flask / Django – Web development
  • TensorFlow / PyTorch – Machine learning

Installing Libraries with pip

sh
pip install numpy

Using a Library

python
import pandas as pd

data = {"name": ["Alice", "Bob"], "age": [25, 30]}
df = pd.DataFrame(data)
print(df)

Creating Your Own Library

You can create a Python file (e.g., mylib.py) and import it into other scripts.

python
# mylib.py
def greet(name):
    return f"Hello, {name}!"
python
import mylib

print(mylib.greet("Alice"))

Best Practices

  • Use virtual environments to manage dependencies
  • Keep libraries up-to-date
  • Prefer well-maintained libraries with good documentation

Conclusion

Python libraries dramatically increase your productivity by providing robust, reusable code components. Whether you're doing data science, web development, or automation, there's a library for nearly every task.