Flow control

Common mistakes to avoid when working with lists

One of the common pitfalls to avoid when working with Python lists is modifying the list while you're iterating over it. This can lead to unexpected results and errors.


Why it's a problem?

Imagine you're looping through your shopping list, removing items as you put them in your cart. Here's what could go wrong:

shopping_list = ["apples", "bread", "milk", "cheese"]

for item in shopping_list:
  if item == "bread":
    shopping_list.remove(item)  # This might cause issues!

print(shopping_list)  # Output might be unexpected (depends on loop implementation)

The problem arises because when you remove "bread" from the list inside the loop, the loop index might become invalid. The loop might skip items or continue iterating even though the list has shrunk.


How to avoid it ?

There are a few ways to ensure safe iteration while modifying a list.

1. Use a copy:

Create a copy of the original list and iterate over the copy. This way, modifications to the copy won't affect the original list and the loop will continue as expected.

shopping_list = ["apples", "bread", "milk", "cheese"]
items_to_buy = shopping_list.copy()  # Create a copy

for item in items_to_buy:
  if item == "bread":
    shopping_list.remove(item)  # Modifying the original list

print(shopping_list)  # Output: ["apples", "milk", "cheese"] (Bread removed)


2. Iterate backwards: 

If you need to remove items from the original list, iterate from the end of the list towards the beginning. Since items are removed from the "back" of the list as you iterate, the loop index remains valid.

shopping_list = ["apples", "bread", "milk", "cheese"]

for i in range(len(shopping_list) - 1, -1, -1):  # Iterate backwards
  if shopping_list[i] == "bread":
    shopping_list.pop(i)  # Removing from the end is safe

print(shopping_list)  # Output: ["apples", "milk", "cheese"] (Bread removed)

It's time to take a quiz!

Test your knowledge and see what you've just learned.

What issue arises from the following code? shopping_list = ["apples", "bread", "milk", "cheese"] for item in shopping_list: if item == "bread": shopping_list.remove(item)

The list will be empty after the loop.
The loop will work correctly.
The loop will skip items after "bread".
The code will raise an error.
Check Answer

What is the purpose of creating a copy of the list in the following code? shopping_list = ["apples", "bread", "milk", "cheese"] items_to_buy = shopping_list.copy() for item in items_to_buy: if item == "bread": shopping_list.remove(item)

To avoid modifying the original list while iterating.
To create a new shopping list.
To speed up the iteration process.
To remove all items from the original list.
Check Answer

What is the benefit of iterating backwards through a list when removing items? shopping_list = ["apples", "bread", "milk", "cheese"] for i in range(len(shopping_list) - 1, -1, -1): if shopping_list[i] == "bread": shopping_list.pop(i)

It allows iteration in reverse order.
It automatically adjusts the loop index.
It prevents index errors when removing items.
It allows for faster removal of items.
Check Answer

What will be the output of the following code? shopping_list = ["apples", "bread", "milk", "cheese"] items_to_buy = shopping_list.copy() for item in items_to_buy: if item == "bread": shopping_list.remove(item) print(shopping_list)

["apples", "milk", "cheese"]
["apples", "bread", "milk", "cheese"]
["milk", "cheese"]
["bread", "milk", "cheese"]
Check Answer