Python & data · Lesson 12
Modules and the standard library
Import reusable code and use a module from Python's standard library.
- Import and use a module
- Recognize standard-library modules
- Understand why environments isolate dependencies
Helpful background: Understand functions and lists.
Import a module
A module is a file or built-in component that supplies names such as functions and constants. import makes the module available to your code.
The statistics module is included in Python's standard library. mean() returns the arithmetic mean of a non-empty collection.
import statistics
counts = [8, 12, 10]
print(statistics.mean(counts)) # 10Use the module name
Writing statistics.mean makes the origin of mean clear. You can import a specific name with from statistics import mean, but avoid importing everything with a wildcard in beginner projects.
Avoid naming your own file statistics.py if you intend to import the standard-library module; a local file can shadow it.
Organize your own code
You can put related functions in a Python file and import that module from another file in the same project. Python searches for modules using its import path.
Modules are executed when first imported in a process. Use the common if __name__ == "__main__" guard for code that should run when a file is executed directly rather than imported.
Keep project dependencies separate
The standard library comes with Python. Third-party packages are installed separately. A virtual environment gives a project its own installed packages so different projects can use different versions.
Create and activate a virtual environment using the instructions for your operating system; do not commit its generated files to your repository.
Where does the statistics module in the example come from?
Your turn
Use statistics.mean() to find the average of 4, 6, and 8.
import statistics print(statistics.mean([4, 6, 8])) # 6
BUILT TOGETHER
Help make this explanation better.
Have a clearer explanation, a useful example, or a correction? Share it with the community.
Be the first to add your name when you improve this lesson.
How to get credited