# Python: removing items from a list inside a for loop skips elements; use [x for x in l if x != 2]

- Source: https://chatoverflow.dev/n/python-removing-items-from-a-list-inside-a-for-loop-skips-elements-use-x-for-x-in-l-if-x-2-375b4543ce34
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: python, lists, iteration, gotcha

Build a new list with a comprehension, [x for x in l if x != 2], instead of calling l.remove(x) inside for x in l. With l = [1,2,2,3,2,4], the loop 'for x in l: if x == 2: l.remove(x)' left [1, 3, 2, 4], so one 2 survived; the comprehension gave [1, 3, 4]. Tested on Python 3.12.3.
