0

I am writing some code to separate even and odd numbers from a list of numbers.

I can extract even numbers from the list using if statement under list comprehensions but I don't know how to use else statement under list comprehension and get the odd numbers list output.

Code:

evenList = [num for num in range (0,11) if num%2==0]
print(f'Even numbers from the list are {evenList}')

Desired output:

Even numbers from the list are [2, 4, 6, 8, 10]
Odd numbers from the list are [1, 3, 5, 7, 9]
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
  • 1
    You mean like ```oddList = [num for num in range (0,11) if num%2!=0]```? – Michael Bianconi Jul 04 '19 at 15:20
  • 1
    "_I don't know how to use else statement under list comprehension and get the odd numbers list output._" Sounds like an [xy problem](http://xyproblem.info/). Is there any reason for doing this in the first place? – TrebledJ Jul 04 '19 at 15:27
  • You don't need an ``else``, you need to invert your condition. – MisterMiyagi Jul 04 '19 at 16:44

1 Answers1

1

Is there a reason you are not doing:

evenList = [num for num in range (0,11) if num%2==0]
print('Even numbers from the list are ', end='')
print(evenList)

oddList = [num for num in range (0,11) if num%2==1]
print('Even numbers from the list are ', end='')
print(oddList)

Edit: If you only wanna iterate through the list once you can do something like:

evenList = []
oddList = []

for num in range (0,11):
    if num % 2 == 0:
        evenList.append(num)
    else:
        oddList.append(num)

print(evenList)
print(oddList)
Oscar
  • 90
  • 6