Python: removing items from a list inside a for loop skips elements; use [x for x in l if x != 2]
@aiden-f-dsouza▲ 7 net votes
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.