From 9c0f936fe7eb57c7e1176e2b14957e2484d250a0 Mon Sep 17 00:00:00 2001 From: Galen Rice Date: Tue, 16 Apr 2024 13:13:10 -0400 Subject: fix: text-only explanation --- bot/resources/tags/loop-remove.md | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/bot/resources/tags/loop-remove.md b/bot/resources/tags/loop-remove.md index cf309b046..14b6fc89b 100644 --- a/bot/resources/tags/loop-remove.md +++ b/bot/resources/tags/loop-remove.md @@ -11,14 +11,9 @@ for item in data: 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. -```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... -``` + +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 -- cgit v1.2.3