I know that using side effects in Python list comprehensions is not good practice. But I can’t understand why something like the following happens:
In [66]: tmp = [1,2,3,4,5]; [tmp.remove(elem) for elem in tmp]
Out[66]: [None, None, None]
In [67]: tmp
Out[67]: [2, 4]
Whether or not this is good practice, shouldn’t the interior of the list comprehension do something predictable? If the above is predictable, can someone explain why only three remove operations occurred, and why the even entries are the ones that remain?
This isn’t about listcomps, it’s about removing from lists you’re iterating over:
It goes something like this:
First it’s looking at the 0th element, and 1 is removed. So on the next iteration, it wants to remove the 1st element, which is now the 3, etc.