-2

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?

jasmin
  • 1
  • 3
    what do you mean by "at the same time" ? – vishal Aug 24 '18 at 11:09
  • 1
    Solution to this question is [Remove all occurrences of a value from a list](https://stackoverflow.com/questions/1157106/remove-all-occurrences-of-a-value-from-a-list) – mdaftab88 Aug 24 '18 at 11:18

3 Answers3

1

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

Sapan Zaveri
  • 490
  • 7
  • 18
0

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.

mcjay
  • 115
  • 1
  • 8
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]
Surya Tej
  • 1,342
  • 2
  • 15
  • 25
  • 2
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Nic3500 Aug 24 '18 at 11:51