How variable type changes at runtime in Python - Performance & Efficiency
We want to see how the time it takes to run code changes when a variable changes its type during the program.
How does this affect the speed as the program runs?
Analyze the time complexity of the following code snippet.
x = 10
x = "hello"
x = [1, 2, 3]
for item in x:
print(item)
This code changes the variable x from a number to a string, then to a list, and finally loops over the list to print each item.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over the list
xto print each item. - How many times: Once for each item in the list (3 times here).
As the list x gets bigger, the loop runs more times, once per item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print operations |
| 100 | 100 print operations |
| 1000 | 1000 print operations |
Pattern observation: The time grows directly with the number of items in the list.
Time Complexity: O(n)
This means the time to run the loop grows in a straight line with the number of items in the list.
[X] Wrong: "Changing the variable type multiple times makes the program slower in a way that depends on the number of changes."
[OK] Correct: Changing the variable type itself is a simple assignment and happens once each time; it does not repeat or grow with input size, so it does not affect the overall time complexity significantly.
Understanding how variable types can change and how loops behave helps you explain how your code runs as data grows, a key skill in many programming tasks.
"What if the variable x was changed to a dictionary instead of a list? How would the time complexity change when looping over it?"