-
-
Save bbookman/b75ae13049a0fc53aa6f27ddd8610f96 to your computer and use it in GitHub Desktop.
''' | |
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)" | |
''' |
[(lambda x: "even" if x % 2 == 0 else "odd")(i) for i in range(20)]
[['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.
# ‘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)
Binary_Class_Separation = ['even' if n%2 == 0 else 'odd' for n in [random.randint(a=0, b=20) for a in range(20)]]
print(Binary_Class_Separation)
res = ['odd' if n%2 else 'even' for n in range(20)]
even_odd = ['Even' if num % 2 == 0 else 'odd' for num in range(21)]
print(even_odd)
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?