r/PythonLearning • • 5d ago

Removing while iterating over a list

Post image

An exercise to help build the right mental model for Python data.

The “Solution” link uses memory_graph to visualize execution and reveals what’s actually happening.

58 Upvotes

14 comments sorted by

9

u/sexiestsaxiestman 5d ago

I guess if you want to understand how Python works. Practically, this is a major antipattern and should never be used.

1

u/Sea-Ad7805 4d ago edited 4d ago

1

u/odimdavid 1d ago

Or better remove from the copy by shallow copy first and use a in the loop. I don't know but since the copy is in a loop I think it's garbaged when the loop ends. That might not be nice. Computers can make mistakes or have a glitch while the loops arunning then everything's lost.

3

u/Hidayat8811 5d ago

I need explanation of this

5

u/DailyDrillsApp 5d ago

It prints [2, 4] [1, 3], so B.

The for loop goes through the list by position. First round it's at index 0, grabs 1 and removes it, so a is now [2, 3, 4]. Next round it moves to index 1, which is now 3, so the 2 gets skipped. After removing 3, a is [2, 4] and there's nothing at index 2 anymore, so the loop just ends. No error, it just quietly skips items.

If you loop over a copy instead (enumerate(a.copy())), you get [] [1, 2, 3, 4].

1

u/Sea-Ad7805 5d ago

Yes, the iteration is index based, look at the index variable to see what the next x value is.

1

u/OskarsSurstromming 5d ago

Is it because of enumerate that it didn't error? I thought that changing a list while looping over it would cause list index out of range

2

u/DailyDrillsApp 5d ago

Nope, enumerate doesn't change anything here, a plain `for x in a:` prints the same `[2, 4] [1, 3]`. The loop keeps an internal position and just stops once that position reaches the list's current length, so it never runs past the end. You'd get the index out of range with `for i in range(len(a)):` plus `a[i]`, since `range(4)` is fixed up front while the list shrinks.

1

u/OskarsSurstromming 5d ago

Okay that makes sense, thank you

1

u/Interesting-Cat3788 4d ago

If I assume that you come from other programming languages, then the concept of enumeration is similar to iterator .

enumeration also gives index along with value, meanwhile iterators in other programming languages only give the underlying value i.e the value at that index which the iterator is pointing to.

So in hindsight, for every element in list, python internally does numerator.next and returns index and value.

But if you modify the list,lets suppose you add into list then this will go forever because there will be always a number to iterate upon.

a = [5]
>>>
>>>
>>> for key,val in enumerate(a):
...     print(a)
...     a.append(1)

>> Output: 5,1,1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, .... forever

This is basically an inifnite loop

Above operation is similar to

a = [10,5]
i= 0

while i<len(a):
    a.append(i)
    i+=1
    print(a[i])

1

u/ChainsawLight 3d ago

I love to practice Leetxode problems on a whiteboard

0

u/Interesting-Cat3788 4d ago

example: scores = [1,5,10,22]

Modifying the list while enumerating on it. Because enumerate creates a pointer to list items and it moves forward as you enumerate further. ( it doesn't hold the copy or have no context of how long the list is)

But range function does, you either pass for x in range(len(scores)) or for x in range(4)

General rule of thumb

Use enumerate if you don't want to modify the list.

1

u/Sea-Ad7805 4d ago

Ehhh, no, use enumerate if you want both the value AND the index.

2

u/Interesting-Cat3788 4d ago

yes, forgot that.