Created
December 26, 2018 22:41
-
-
Save bbookman/b75ae13049a0fc53aa6f27ddd8610f96 to your computer and use it in GitHub Desktop.
Python List Comprehension: Determine even or odd in list of numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
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)" | |
''' |
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)]
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
# ‘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)