0
0
Pythonprogramming~5 mins

Iterating over lists in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Iterating over lists
O(n)
Understanding Time Complexity

When we go through each item in a list one by one, it takes some time. We want to understand how this time changes when the list gets bigger.

The question is: How does the time to look at every item grow as the list grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

def print_items(items):
    for item in items:
        print(item)

my_list = [1, 2, 3, 4, 5]
print_items(my_list)

This code goes through each item in a list and prints it out.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each item in the list.
  • How many times: Once for every item in the list.
How Execution Grows With Input

As the list gets bigger, the number of times we print grows the same way.

Input Size (n)Approx. Operations
1010 prints
100100 prints
10001000 prints

Pattern observation: The number of steps grows directly with the size of the list.

Final Time Complexity

Time Complexity: O(n)

This means if the list doubles in size, the time to go through it also doubles.

Common Mistake

[X] Wrong: "Looping through a list always takes the same time no matter how big the list is."

[OK] Correct: The time depends on how many items are in the list. More items mean more steps.

Interview Connect

Understanding how looping through lists grows with size helps you explain your code clearly and shows you know how programs handle data efficiently.

Self-Check

"What if we nested one loop inside another to go through the list twice? How would the time complexity change?"