Why Python is easy to learn - Performance Analysis
We want to see how the time it takes to run Python code grows as the code gets bigger or more complex.
How does Python's design help keep things simple and fast to learn?
Analyze the time complexity of the following code snippet.
def greet(names):
for name in names:
print(f'Hello, {name}!')
people = ['Alice', 'Bob', 'Charlie']
greet(people)
This code says hello to each person in a list by printing a message.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of names.
- How many times: Once for each name in the list.
As the list of names grows, the number of greetings grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 greetings |
| 100 | 100 greetings |
| 1000 | 1000 greetings |
Pattern observation: The work grows directly with the number of names.
Time Complexity: O(n)
This means the time to run the code grows in a straight line with the input size.
[X] Wrong: "Python is slow because it uses loops for everything."
[OK] Correct: Python's simple loops make it easy to understand how time grows, and many tasks run in straight lines, not slow nested loops.
Knowing how Python's simple structures grow with input helps you explain your code clearly and shows you understand how programs work behind the scenes.
"What if we changed the list to a nested list of names? How would the time complexity change?"