One-line list comprehension: if-else variants

It’s more about python list comprehension syntax. I’ve got a list comprehension that produces list of odd numbers of a given range:

[x for x in range(1, 10) if x % 2]

This makes a filter – I’ve got a source list, where I remove even numbers (if x % 2). I’d like to use something like if-then-else here. Following code fails:

>>> [x for x in range(1, 10) if x % 2 else x * 100]
  File "<stdin>", line 1
    [x for x in range(1, 10) if x % 2 else x * 100]
                                         ^
SyntaxError: invalid syntax

There is a python expression like if-else:

1 if 0 is 0 else 3

How to use it inside a list comprehension?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

x if y else z is the syntax for the expression you’re returning for each element. Thus you need:

[ x if x%2 else x*100 for x in range(1, 10) ]

The confusion arises from the fact you’re using a filter in the first example, but not in the second. In the second example you’re only mapping each value to another, using a ternary-operator expression.

With a filter, you need:

[ EXP for x in seq if COND ]

Without a filter you need:

[ EXP for x in seq ]

and in your second example, the expression is a “complex” one, which happens to involve an if-else.

Method 2

[x if x % 2 else x * 100 for x in range(1, 10) ]

Method 3

You can do that with list comprehension too:

A=[[x*100, x][x % 2 != 0] for x in range(1,11)]
print A

Method 4

Just another solution, hope some one may like it :

Using: [False, True][Expression]

>>> map(lambda x: [x*100, x][x % 2 != 0], range(1,10))
[1, 200, 3, 400, 5, 600, 7, 800, 9]
>>>

Method 5

#how you can squre a list of an array of negative and positive values

my_list=[-2,-3,0,1,5]
squred_values=[]
  

squred_values=[-i**2 if i<0 else i**2 for i in my_list]

#or

for i in my_list:
    if i<0:
        squred_values.append( -i**2)`enter code here`
    else:
        squred_values.append( i**2)

Method 6

two for in one list comprehension

ex = [['obi', 'is', '#alive'],['oge', 'is', 'beautiful'],
                ['Ade', 'the', '#comedian', 'de', '#rich'],['Jesus', 'wept']]
res = [j if j.startswith("#") else "_"+j for i in ex for j in i]


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x