-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIterateListBehavior.py
More file actions
21 lines (18 loc) · 874 Bytes
/
IterateListBehavior.py
File metadata and controls
21 lines (18 loc) · 874 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Unexpected behavior in your loops while iterating over a list
# -------------------------------------------------------------------------------------------------------------------------------
items = ['A', 'B', 'C', 'D', 'E']
for item in items:
if item == 'B':
items.remove('B') # This will cause an issue
else:
print(item)
# The above code will skip 'C' because the list is modified during iteration.
# To avoid this, iterate over a copy of the list or use a different approach.
# -------------------------------------------------------------------------------------------------------------------------------
new_items = [] # Temporary list to hold items
for item in items:
if item == 'B':
continue # Skip 'B' without modifying the original list
else:
print(item)
new_items.append(item)