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
27 changes: 27 additions & 0 deletions bot/resources/tags/loop-remove.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
---
aliases: ["loop-add", "loop-modify"]
embed:
title: "Removing items inside a for loop"
---
Avoid adding to or removing 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!
```
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.

In the example above, `1` is removed, shifting `2` to index *0*. The loop then moves to index *1*, removing `3` (and skipping `2`!).

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