Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: tag loop-remove #3018

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
31 changes: 31 additions & 0 deletions bot/resources/tags/loop-remove.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
---
embed:
title: "Removing items inside a for loop"
---
Avoid removing items from a collection, such as a list, as you iterate that collection in a `for` loop:
```py
data = [1, 2, 3, 4]
for item in data:
data.remove(item)
print(data) # [2, 4] <-- every OTHER item was removed!
```
`for` loops track the index of the current item with a kind of pointer. Removing an element causes all other elements to shift, but the pointer is not changed:
GriceTurrble marked this conversation as resolved.
Show resolved Hide resolved
```py
[1, 2, 3, 4] # First iteration: point to the first element
^
[2, 3, 4] # Remove current: all elements shift
^
[2, 3, 4] # Next iteration: move the pointer
^ # and so on...
```
You can avoid this pitfall by:
- using a **list comprehension** to produce a new list (as a way of filtering items):
```py
data = [x for x in data if x % 2 == 0]
```
- using a `while` loop and `.pop()` (treating the list as a stack):
```py
while data:
item = data.pop()
```
- considering whether you need to remove items in the first place!
Loading