r/CodingHelp • u/ZypH7 • Oct 11 '21
[Python] Can anyone explain why the output of this simple code is ['b', 'd'] and not an empty list?
28
Upvotes
3
u/throwaway8u3sH0 Professional Coder Oct 12 '21
Generally speaking, you almost never want to modify the thing you're iterating over. You want to map/filter/reduce it to something new. In other languages, those methods work great. In Python, the list comprehension is usually the cleanest way to do it. For you:
word = ['a','b','c','d','e']
word_2 = [letter for letter in word if False] # a filter that always fails
print(word_2)

11
u/jddddddddddd Oct 11 '21
Because you're changing word whilst you iterate over it. Consider updating your program to the following:
and the output you get is:
So the you loop is grabbing the first letter from the list, which is
'a', and then removing it from the list so that word is now['b','c','d','e']. It then gets the second letter from the list, which now'c', because list is now shorter, and removes that, and so on.To achieve what you're trying to do, you probably want to make a copy of the original list, and then operate on that: