0

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.

Vivek
  • 175
  • 1
  • 9
  • 1
    Possible duplicate of [if/else in Python's list comprehension?](https://stackoverflow.com/questions/4260280/if-else-in-pythons-list-comprehension) – dennlinger Jul 13 '18 at 05:41

4 Answers4

2

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.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
0

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']
Kaushik NP
  • 6,733
  • 9
  • 31
  • 60
0
['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.

Sushant
  • 3,499
  • 3
  • 17
  • 34
-1

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']

Om trivedi
  • 32
  • 3