Skip to content

Instantly share code, notes, and snippets.

@bbookman
Created December 26, 2018 22:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbookman/b75ae13049a0fc53aa6f27ddd8610f96 to your computer and use it in GitHub Desktop.
Save bbookman/b75ae13049a0fc53aa6f27ddd8610f96 to your computer and use it in GitHub Desktop.
Python List Comprehension: Determine even or odd in list of numbers
'''
Given numbers = range(20), produce a list containing the word 'even' if a number in the numbers is even, and the word 'odd' if the number is odd. Result would look like ['odd','odd', 'even']
'''
result = ['even' if n%2 == 0 else 'odd' for n in range(20)]
print(result)
'''
Let's see the for loop and break out the syntax of the list comprehension
'''
result = []
for n in range(20):
if n % 2 == 0:
result.append('even')
else:
result.append('odd')
'''
List comprehension
[expression for item in list]
expression = "'even' if n %2 == 0 else 'odd'"
for item in list = "for n in range(20)"
'''
@avanoc
Copy link

avanoc commented Dec 2, 2022

So in this case, you change the order and put the conditional first, am I right?
If there's no else condition, then the list comprehension would look like:
result = ["even" for n in range(20) if n%2 == 0]
but since it exists the condition n%2 == 0 is checked first...
Is it always like this? Or is it another way to present this list comprehension?

@0xb1b1
Copy link

0xb1b1 commented May 23, 2023

[(lambda x: "even" if x % 2 == 0 else "odd")(i) for i in range(20)]

@OmikronWeapon
Copy link

[['even','odd'][x%2] for x in numbers]
I did it like this. While I'm sure most people here will understand, the notation makes reading it a little weird, so I'll explain, just in case. I used the modulo of x as the index for a list ['even', 'odd']
I'd also like to thank Bruce for this list of exercises, it's exactly what I needed to practice beyond my coursebook.

@Amine-Fadssi
Copy link

# ‘even’ if a number in the numbers is even, else ‘odd’
my_list = ['even' if num % 2 == 0 else 'odd' for num in range(20)]
print(my_list)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment