Why does my code not remove the last empty element in the list?
templist = ['', 'hello', '', 'hi', 'mkay', '', '']
for element in templist:
if element == '':
templist.remove(element)
print (templist)
Output:
['hello', 'hi', 'mkay', '']
Well, you could always just do this:
new_list = list(filter(None, templist))
Because you are mutating the list that is being iterating over. Think of it as if the for loop is iterating using an index; removing elements reduces the length of the list thereby invalidating indices > len(list) - 1
.
The "Pythonic" solution to this is to use a list comprehension:
templist = ['', 'hello', '', 'hi', 'mkay', '', '']
templist[:] = [item for item in templist if item != '']
This performs in place removal of items from the list.
To point out your error, by iterating through a copy of the list, i.e changing your for
statement to:
for element in templist[:]:
Altering a list while you iterate over it leads to the odd results you see.
More compactly, you could use filter
for this:
templist = list(filter(None, templist))
when None
is supplied to it, it simply returns elements that are true (empty strings evaluate to false).
You could make a new list called wordGrabber
for example and instead of removing the blanks you could populate your new list with content
templist = ['', 'hello', '', 'hi', 'mkay', '', '']
for element in templist:
if element != '':
wordGrabber.append(element)
print (wordGrabber)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With