List Comprehension Flashcards
__________________ are a unique way of quickly creating a list with python.
If you find yourself using a for loop along with .append() to create a list, this is a good alternative!
List comprehension
mystring = ‘hello’
Make a list of all the characters in mystring in a less efficient way then using list comprehension.
less efficient:
list = []
for letter in mystring:
list.append(letter)
list
list comprehension:
list = [letter for letter in mystring]
- Make a list of numbers from 0 - 10 using list comprehension.
- Now make a list of the squares of the list of #1.
1)
numbers = [num for num in range(0,11)]
numbers
2)
numbers = [num**2 for num in range(0,11)]
numbers
Make a list of the even squares from 0 - 10 using list comprehension.
evenlist = [num**2 for num in range(0,11) if num%2 == 0]
Make a list of numbers from 0 - 10 where the odd numbers are stored as ODD using list comprehension.
results = [x if x%2==0 else ‘ODD’ for x in range(0,11)]
Note: For if-else statements are the reverse arrangement of just ‘if’ statements.