Avoid Modifying a List While Iterating Over It in Python

To avoid modifying a list while iterating over it, you can iterate over a copy of the list using slicing, the copy() method, or the list() constructor. Another approach is to use list comprehension or store elements for later modification instead of altering the list in place during iteration.


Examples

1. Iterating Over a Copy Using Slicing

Using list slicing [:], we create a copy of the list before iterating over it. This ensures that modifications to the original list do not affect the iteration process.

</>
Copy
# Original list
numbers = [1, 2, 3, 4, 5]

# Iterating over a copy using slicing
for num in numbers[:]:
    if num % 2 == 0:
        numbers.remove(num)  # Remove even numbers

# Printing the updated list
print("Modified List:", numbers)

In this example:

  1. The list numbers contains integers.
  2. We iterate over a copy of numbers using numbers[:].
  3. Even numbers are removed from the original numbers list.

Output:

Modified List: [1, 3, 5]

2. Using the copy() Method

The copy() method creates a shallow copy of the list, preventing unintended modifications while iterating.

</>
Copy
# Original list
words = ["apple", "banana", "cherry", "date"]

# Iterating over a copied list
for word in words.copy():
    if "a" in word:
        words.remove(word)  # Remove words containing 'a'

# Printing the updated list
print("Modified List:", words)

In this example:

  1. The list words contains strings.
  2. We iterate over a shallow copy of the list using words.copy().
  3. Words containing the letter ‘a’ are removed from the original words list.

Output:

Modified List: ['cherry']

3. Using the list() Constructor

The list() constructor creates a new list from an iterable, allowing safe iteration while modifying the original list.

</>
Copy
# Original list
items = ["pen", "pencil", "eraser", "marker"]

# Iterating over a new list created using list()
for item in list(items):
    if len(item) > 5:
        items.remove(item)  # Remove items with more than 5 characters

# Printing the updated list
print("Modified List:", items)

In this example:

  1. The list items contains words.
  2. We iterate over a new list created using list(items).
  3. Items with more than five characters are removed from the original items list.

Output:

Modified List: ['pen', 'eraser']

4. Using List Comprehension

List comprehension provides a clean way to create a modified list without modifying the original list during iteration.

</>
Copy
# Original list
numbers = [10, 15, 20, 25, 30]

# Creating a new filtered list using list comprehension
filtered_numbers = [num for num in numbers if num % 10 != 0]

# Printing the updated list
print("Filtered List:", filtered_numbers)

In this example:

  1. The list numbers contains integers.
  2. We use list comprehension to create a new list that excludes numbers divisible by 10.
  3. The original list remains unchanged.

Output:

Filtered List: [15, 25]

Conclusion

To avoid modifying a list while iterating over it, you can use:

  1. List Slicing ([:]): Iterates over a copy to prevent issues.
  2. copy() Method: Creates a shallow copy for safe iteration.
  3. list() Constructor: Generates a new iterable for iteration.
  4. List Comprehension: Forms a new list without modifying the original.