简体   繁体   中英

Python list comprehension: assigning values in if else statement

I am trying to write a List comprehension for below for loop in python

num_list = []

for num in range(10):
if num % 2 == 0:
    num_list.append('EVEN')
else:
    num_list.append('ODD')

I wrote something like

[num if num % 2 == 0  'EVEN' else 'ODD' for num in range(10)]

and

[num if num % 2 == 0  then 'EVEN' else 'ODD' for num in range(10)]

but both are giving syntax errors and not valid.

I am new to pyhton, so not sure if this can be translated to a comprehension or not. Any help would be appreciated.

Ternary expressions work slightly differently:

['EVEN' if num % 2 == 0 else 'ODD' for num in range(10)]

although I think

['ODD' if num % 2 else 'EVEN' for num in range(10)]

looks nicer.

Think of it this way:

[('ODD' if num % 2 else 'EVEN') for num in range(10)]

The brackets can be used for clarification, but they are not necessary and might confuse people into thinking you're building tuples or a generator expression.

It should be :

>>> ['EVEN' if num%2 == 0 else 'ODD' for num in range(10)]

#driver values

OUT : ['EVEN', 'ODD', 'EVEN', 'ODD', 'EVEN', 'ODD', 'EVEN', 'ODD', 'EVEN', 'ODD']
['EVEN' if num % 2 == 0 else 'ODD' for num in range(10)]

so ideally what we need to return or push into list is from where the list comprehension starts. Let's try to build it from your for loop -

num_list = []

for num in range(10):            #  for num in range(10) (third part)
    if num % 2 == 0:
        num_list.append('EVEN')  # 'EVEN' if num % 2 == 0 (first part)
    else:
        num_list.append('ODD')   #  else 'ODD' (second part)

You could take a look at this to understand list comprehension more.

If you want to know which number is even or odd then you try this

print([str(nub) + ' Odd' if nub % 2 != 0 else str(nub) + ' Even' for nub in range(1, 11)])

Output:['1 Odd', '2 Even', '3 Odd', '4 Even', '5 Odd', '6 Even', '7 Odd', '8 Even', '9 Odd', '10 Even']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM