Let's learn more cool Python stuff.
Now we're going to learn about list comprehensions.
A list comprehension is kind of like a reverse for-loop. It makes it easy to do operations on elements in a list and return a new list.
Say we have a list of numbers:
my_favorite_numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Now let's make a new list that contains a square of every number in our list.
squared_numbers = []
for n in my_favorite_numbers:
squared_numbers.append(n * n)
squared_numbers
Stop for questions?: Does this look familiar? Any questions about this?
Now let's do the same thing by using a list comprehension instead:
squared_numbers = [n * n for n in my_favorite_numbers]
squared_numbers
Note how our list comprehension is written within the brackets: The for-loop statement is written at the end whereas the action inside of the for-loop is written first: n * n
Let's revisit a problem we've already solved in Danny's lecture on list:
Pick every name from a list that begins with a vowel.
We started with a list of names first:
names = ["Danny", "Audrey", "Rise", "Alain"]
Then we filtered names like this:
vowel_names = []
for name in names:
if name[0] in "AEIOU":
vowel_names.append(name)
vowel_names
Here's another way to grab all names starting with a vowel, using list comprehensions:
vowel_names = [name for name in names if name[0] in "AEIOU"]
vowel_names
Unlike lists, dictionaries are indexed by keys. Dictionaries can be used to represent unordered key-value pairs. Keys are unique and are used for looking up values assigned to them.
Let's make a Spanish to English translator. We'll ignore grammar and just translate word-by-word for now.
words = {
'gato': "cat",
'casa': "house",
'esta': "is",
'en': "in",
'el': "the",
'la': "the",
}
words['gato']
Similar to lists and strings, you can check whether a dictionary contains a given key.
'gato' in words
We can also check how many key-value pairs are in our dictionary:
len(words)
Strings have a split method which we can use to split strings with spaces into a list of words.
sentence = "el gato esta en la casa"
sentence_words = sentence.split()
sentence_words
Let's translate each word and save them in the list called translated_words. We'll generate this list by using a list comprehension.
translated_words = [print(words[spanish_word]) for spanish_word in sentence_words]
translated_words
We've almost made a translated sentence! Let's join our new list of words back together with spaces in between each word.
translated_sentence = " ".join(translated_words)
translated_sentence
Let's put this all together into a function:
words = {
'gato': "cat",
'perro': "dog",
'casa': "house",
'burrito': "burrito",
'verde': "green",
'comio': "ate",
'esta': "is",
'en': "in",
'el': "the",
'la': "the",
}
def translate(sentence):
spanish_words = sentence.split()
english_words = []
for w in spanish_words:
english_words.append(words[w])
return " ".join(english_words)
translate("el perro comio el burrito verde")
translate("el burrito comio el perro verde")
translate("el gato comio la casa")
Extra Credit: Try using a list comprehension in the translate function.
Sets are unordered collections of distinct items. Lists can have duplicates of the same item, but sets only store one copy.
Let's say we want to make a roster of people who have RSVPed to our birthday party. If someone RSVPs twice, we don't want them showing up in our roster twice. Let's use a set!
party_roster = {"Jessica", "Tom", "Alice"}
party_roster
Notice how we used curly braces around our set (just like we did for dictionaries)? What happens if we want to represent an empty set?
empty_dictionary = {}
type(empty_dictionary)
empty_set = set()
type(empty_set)
Our friend Jeremy just RSVPed, let's add him to our set too:
party_roster.add("Jeremy")
We can check for size and membership of sets and loop over them just like with sets, strings, and dictionaries.
"Jessica" in party_roster
"Bill" in party_roster
len(party_roster)
Our party is a potluck. Everyone is supposed to bring a dinner dish or a dessert. Let's make sets for everyone bringing a dish and everyone bringing a dessert.
bringing_dish = {"Jessica", "Jeremy"}
bringing_dessert = {"Alice", "Jeremy"}
Sets allow us to use set operations from math to find the union, intersection, difference, and symmetric difference between sets. Let's try it out:
bringing_dish_or_dessert = bringing_dish.union(bringing_dessert)
bringing_dish_and_dessert = bringing_dish.intersection(bringing_dessert)
bringing_just_one_item = bringing_dish.symmetric_difference(bringing_dessert)
not_bringing_food = party_roster.difference(bringing_dish_or_dessert)
print(bringing_dish_or_dessert)
print(bringing_dish_and_dessert)
print(bringing_just_one_item)
print(not_bringing_food)