r/PythonLearning • • 2h 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.

2 Upvotes

2 comments sorted by

1

u/Hidayat8811 1h ago

I need explanation of this

2

u/DailyDrillsApp 44m 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].