Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension with condition

I have a simple list.

>>> a = [0, 1, 2]

I want to make a new list from it using a list comprehension.

>>> b = [x*2 for x in a]
>>> b
[0, 2, 4]

Pretty simple, but what if I want to operate only over nonzero elements?

'if' needs 'else' in list comprehensions, so I came up with this.

>>> b = [x*2 if x != 0 else None for x in a]
>>> b
[None, 2, 4]

But the desirable result is.

>>> b
[2, 4]

I can do that this way

>>> a = [0, 1, 2]
>>> def f(arg):
...     for x in arg:
...         if x != 0:
...             yield x*2
... 
>>> list(f(a))
[2, 4]

or using 'filter' and a lambda

>>> a = [0, 1, 2]
>>> list(filter(lambda x: x != 0, a))
[1, 2]

How do I get this result using a list comprehension?

like image 265
selurvedu Avatar asked Jun 26 '14 23:06

selurvedu


2 Answers

b = [x*2 for x in a if x != 0]

if you put your condition at the end you do not need an else (infact cannot have an else there)

like image 59
Joran Beasley Avatar answered Nov 11 '22 17:11

Joran Beasley


Following the pattern:

[ <item_expression>
  for <item_variables> in <iterator>
  if <filtering_condition>
]

we can solve it like:

>>> lst = [0, 1, 2]
>>> [num
... for num in lst
... if num != 0]
[1, 2]

It is all about forming an if condition testing "nonzero" value.

like image 45
Jan Vlcinsky Avatar answered Nov 11 '22 17:11

Jan Vlcinsky