Type conversion (int, float, string) in Python - Time & Space Complexity
We want to understand how the time it takes to convert data types changes as the input size grows.
How does converting numbers or text take more or less time when the input is bigger?
Analyze the time complexity of the following code snippet.
text_numbers = ["123", "456", "789"]
converted = []
for num_str in text_numbers:
converted.append(int(num_str))
This code converts a list of strings representing numbers into integers one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Converting each string to an integer inside a loop.
- How many times: Once for each item in the list.
As the list gets longer, the number of conversions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 conversions |
| 100 | 100 conversions |
| 1000 | 1000 conversions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n * m)
This means the time to convert grows linearly with the number of items and the length of each string.
[X] Wrong: "Converting a string to an int always takes the same time no matter how many items there are or how long the strings are."
[OK] Correct: Each conversion takes time proportional to the length of the string, so longer strings or more items mean more total time.
Understanding how simple operations like type conversion scale helps you explain your code's efficiency clearly and confidently.
"What if we converted a single very long string number instead of many short ones? How would the time complexity change?"