Importing specific items in Python - Time & Space Complexity
When we import specific items in Python, we want to know how this affects the program's speed as it runs.
We ask: How does the time to import grow when we import parts of a module?
Analyze the time complexity of the following code snippet.
from math import sqrt, factorial
result1 = sqrt(16)
result2 = factorial(5)
print(result1, result2)
This code imports only two specific functions from the math module and uses them.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Importing the specified functions from the module.
- How many times: This happens once when the program starts.
Importing specific items happens once and does not repeat with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Constant time to import specified items |
| 100 | Still constant time, no change |
| 1000 | Still constant time, no change |
Pattern observation: The time to import specific items does not grow with input size; it stays the same.
Time Complexity: O(1)
This means importing specific items takes the same amount of time no matter how big the input is.
[X] Wrong: "Importing specific items takes longer as the program runs or input grows."
[OK] Correct: Importing happens once at the start, so it does not repeat or grow with input size.
Understanding how imports work helps you write efficient code and explain program behavior clearly.
"What if we imported an entire large module instead of specific items? How would the time complexity change?"