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.
# 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:
- The list
numbers
contains integers. - We iterate over a copy of
numbers
usingnumbers[:]
. - 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.
# 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:
- The list
words
contains strings. - We iterate over a shallow copy of the list using
words.copy()
. - 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.
# 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:
- The list
items
contains words. - We iterate over a new list created using
list(items)
. - 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.
# 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:
- The list
numbers
contains integers. - We use list comprehension to create a new list that excludes numbers divisible by 10.
- The original list remains unchanged.
Output:
Filtered List: [15, 25]
Conclusion
To avoid modifying a list while iterating over it, you can use:
- List Slicing (
[:]
): Iterates over a copy to prevent issues. copy()
Method: Creates a shallow copy for safe iteration.list()
Constructor: Generates a new iterable for iteration.- List Comprehension: Forms a new list without modifying the original.