Let's say i have a=[1,0,1,0,1,1,1,0,0,0,0]
I want to remove all the zero's at the same time. can i do that?
Let's say i have a=[1,0,1,0,1,1,1,0,0,0,0]
I want to remove all the zero's at the same time. can i do that?
There are multiple solution to do that. As list comprehension is already explained I am trying something different. Using lambda function
Python 2.x
>>> x = [1,0,1,0,1,1,1,0,0,0,0]
>>> filter(lambda a: a != 0, x)
[1, 1, 1, 1, 1]
Python 3.x or above
>>> x = [1,0,1,0,1,1,1,0,0,0,0]
>>> list(filter((0).__ne__, x))
[1, 1, 1, 1, 1]
or
>>> x = [1,0,1,0,1,1,1,0,0,0,0]
>>> list(filter(lambda a: a != 0, x))
[1, 1, 1, 1, 1]
Hope it helps :)
You can use list comprehension for that:
a=[1,0,1,0,1,1,1,0,0,0,0]
print([value for value in a if value != 0])
This will remove all elements from list with value equal to 0.
a=[1,0,1,0,1,1,1,0,0,0,0]
b = [x for x in a if x!= 0]
>>> b
[1, 1, 1, 1, 1]