Import aliasing in Python - Time & Space Complexity
We want to see how the time it takes to run code changes when we use import aliasing in Python.
Does giving a shorter name to an imported module affect how fast the program runs?
Analyze the time complexity of the following code snippet.
import math as m
def calculate_squares(numbers):
result = []
for num in numbers:
result.append(m.sqrt(num) ** 2)
return result
This code imports the math module with a short name and uses it to calculate squares of square roots for a list of numbers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of numbers and calling the square root function for each.
- How many times: Once for each number in the input list.
As the list of numbers grows, the program does more square root calculations, one for each number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 square root calculations |
| 100 | 100 square root calculations |
| 1000 | 1000 square root calculations |
Pattern observation: The number of operations grows directly with the number of input items.
Time Complexity: O(n)
This means the time to run the code grows in a straight line as the input list gets bigger.
[X] Wrong: "Using an alias for the import makes the code run faster."
[OK] Correct: The alias is just a shortcut for typing. It does not change how many times the code runs or how long each operation takes.
Understanding how import aliasing affects performance helps you explain code clarity versus speed in interviews. It shows you know that naming shortcuts don't speed up the actual work done.
"What if we replaced the loop with a list comprehension? How would the time complexity change?"