3
#!/usr/bin/python

x = [0, 2, 1, 1, 1, 1, 3, 3, 5, 1, 1, 4, 1, 2, 1, 2, 2, 2, 1, 7, 2, 1, 0, 3, 1, 1, 2, 0, 1, 0, 1, 1]

y = [1 for z in x if z > 0]

#WANT TO DO
#y = [1 for z in x if z > 0 else 0]

I want to do both an if statement and an else statement within a list comprehension in Python. How can I do this?

I figured out y = [int(bool(z)) for z in x], but i was wondering if you could do both an if and an else statement in a list comprehension.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
O.rka
  • 29,847
  • 68
  • 194
  • 309
  • 3
    Do you mean `[1 if z > 0 else 0 for z in x]`? The expression on the right-hand side of the `for foo in bar` is for *filtering*, on the left-hand side is for *mapping*. – jonrsharpe Aug 05 '15 at 17:49
  • 1
    Better dupe: http://stackoverflow.com/q/2951701/3001761 – jonrsharpe Aug 05 '15 at 17:57

2 Answers2

2

You can do it on the left-hand side of the list comprehension (that is, the statement before the for keyword:

y = [1 if z > 0 else 0 for z in x]
mipadi
  • 398,885
  • 90
  • 523
  • 479
1

Yes it's possible here is an example:

y = [1 if z > 0 else 'test' for z in x ]

This thread also provides a few more details about it.

Community
  • 1
  • 1
Jean Guzman
  • 2,162
  • 1
  • 17
  • 27