r/PythonLearning • u/Sea-Ad7805 • 2d ago
Removing while iterating over a list
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.
29
Upvotes
9
u/sexiestsaxiestman 1d ago
I guess if you want to understand how Python works. Practically, this is a major antipattern and should never be used.
2
u/Hidayat8811 2d ago
I need explanation of this
0
u/Interesting-Cat3788 1d 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))orfor x in range(4)General rule of thumb
Use enumerate if you don't want to modify the list.