Skip to content

Commit 9c0f936

Browse files
author
Galen Rice
authored
fix: text-only explanation
1 parent d3e2538 commit 9c0f936

File tree

1 file changed

+3
-8
lines changed

1 file changed

+3
-8
lines changed

bot/resources/tags/loop-remove.md

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,9 @@ for item in data:
1111
print(data) # [2, 4] <-- every OTHER item was removed!
1212
```
1313
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-
```py
15-
[1, 2, 3, 4] # First iteration: point to the first element
16-
^
17-
[2, 3, 4] # Remove current: all elements shift
18-
^
19-
[2, 3, 4] # Next iteration: move the pointer
20-
^ # and so on...
21-
```
14+
15+
Above, `1` is removed, shifting `2` to index *0*. The loop then moves to index *1*, removing `3` (and skipping `2`!).
16+
2217
You can avoid this pitfall by:
2318
- using a **list comprehension** to produce a new list (as a way of filtering items):
2419
```py

0 commit comments

Comments
 (0)