Dec-18-2020, 10:02 PM
As bowlofred mentions, the two examples not only solve the problem in different ways, but produce different results. The difference may be an unimportant side-effect, or it might break your code.
nr = 9 numbers = [0,5,6,7,6,9,9,1,9] # This createa a new list nines = [x for x in numbers if x == nr] print('New List', nines, numbers) # This code modifies the list nines = numbers for x in nines[:]: if x != nr: nines.remove(x) print('Modifies', nines, numbers)
Output:New List [9, 9, 9] [0, 5, 6, 7, 6, 9, 9, 1, 9]
Modifies [9, 9, 9] [9, 9, 9]
Notice that the list comprehension does not change the original list. The remove.() for loop looks clunky, but it does modify the original list. All references to the list will see the changes.