Skip to content

Commit 9567ddd

Browse files
Merge pull request #3018 from python-discord/feat/tag-list-iterate-and-remove-gotcha
feat: tag loop-remove
2 parents 9dc2aea + 2822896 commit 9567ddd

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

bot/resources/tags/loop-remove.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
---
2+
aliases: ["loop-add", "loop-modify"]
3+
embed:
4+
title: "Removing items inside a for loop"
5+
---
6+
Avoid adding to or removing from a collection, such as a list, as you iterate that collection in a `for` loop:
7+
```py
8+
data = [1, 2, 3, 4]
9+
for item in data:
10+
data.remove(item)
11+
print(data) # [2, 4] <-- every OTHER item was removed!
12+
```
13+
Inside the loop, an index tracks the current position. If the list is modified, this index may no longer refer to the same element, causing elements to be repeated or skipped.
14+
15+
In the example above, `1` is removed, shifting `2` to index *0*. The loop then moves to index *1*, removing `3` (and skipping `2`!).
16+
17+
You can avoid this pitfall by:
18+
- using a **list comprehension** to produce a new list (as a way of filtering items):
19+
```py
20+
data = [x for x in data if x % 2 == 0]
21+
```
22+
- using a `while` loop and `.pop()` (treating the list as a stack):
23+
```py
24+
while data:
25+
item = data.pop()
26+
```
27+
- considering whether you need to remove items in the first place!

0 commit comments

Comments
 (0)