Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing all empty elements from a list [duplicate]

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', '']
like image 681
Clone Avatar asked Nov 14 '16 21:11

Clone


4 Answers

Well, you could always just do this:

new_list = list(filter(None, templist))
like image 138
Elliot Roberts Avatar answered Oct 26 '22 11:10

Elliot Roberts


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.

like image 43
mhawke Avatar answered Oct 26 '22 09:10

mhawke


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).

like image 27
Dimitris Fasarakis Hilliard Avatar answered Oct 26 '22 10:10

Dimitris Fasarakis Hilliard


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)
like image 40
computeriscomputer Avatar answered Oct 26 '22 10:10

computeriscomputer