Reputation: 19
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]
Upvotes: 0
Views: 493
Reputation: 90
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)
Upvotes: 1