Let's learn more cool Python stuff.
Say we have a list of numbers:
In [ ]:
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.
In [ ]:
squared_numbers = []
for n in my_favorite_numbers:
squared_numbers.append(n * n)
In [ ]:
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:
In [ ]:
squared_numbers = [n * n for n in my_favorite_numbers]
In [ ]:
squared_numbers
Note how our list comprehension is written within the brackets: The list we're looping over (my_favorite_numbers) is written at the end whereas the action inside of the for-loop is written first: n * n
First written as a conventional 'for' loop:
squared_numbers = [] for n in my_favorite_numbers: squared_numbers.append(n * n)
And then written as a list comprehension:
squared_numbers = [n * n for n in my_favorite_numbers]
Look for the new list being created, the iteration being done over the orignal list and the transformation being done on each element. List comprehensions are just a cleaner way of building lists from other iterables.
In [ ]:
names = ["Danny", "Audrey", "Rise", "Alain"]
Then we filtered names like this:
In [ ]:
vowel_names = []
for name in names:
if name[0] in "AEIOU":
vowel_names.append(name)
In [ ]:
vowel_names
Here's another way to grab all names starting with a vowel, using list comprehensions:
In [ ]:
vowel_names = [name for name in names if name[0] in "AEIOU"]
In [ ]:
vowel_names
In [ ]:
words = {
'gato': "cat",
'casa': "house",
'esta': "is",
'en': "in",
'el': "the",
'la': "the",
}
In [ ]:
words['gato']
Similar to lists and strings, you can check whether a dictionary contains a given key.
In [ ]:
'gato' in words
We can also reassign keys in our dictionary:
In [ ]:
words['gato'] = "dog"
words['gato']
Let's change that back so we don't confuse anyone:
In [ ]:
words['gato'] = "cat"
We can also check how many key-value pairs are in our dictionary:
In [ ]:
len(words)
Strings have a split method which we can use to split strings with spaces into a list of words.
In [ ]:
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. Let's start with an empty list and use a for loop to populate our list:
In [ ]:
translated_words = []
for spanish_word in sentence_words:
translated_words.append(words[spanish_word])
In [ ]:
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.
In [ ]:
translated_sentence = " ".join(translated_words)
translated_sentence
Let's put this all together into a function:
In [ ]:
words = {
'gato': "cat",
'casa': "house",
'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)
In [ ]:
translate("el gato esta en la casa")
Let's add another word to our dictionary:
In [ ]:
words['jugo'] = "juice"
In [ ]:
translate("el jugo esta en la casa")
That's how we say juice in Mexican Spanish but what if we're traveling to Spain? Let's remove jugo from our dictionary and add zumo:
In [ ]:
del words['jugo']
words['zumo'] = "juice"
Let's try our Mexican Spanish sentence again. What should happen?
In [ ]:
translate("el jugo esta en la casa")
Now let's try our Spanish Spanish sentence:
In [ ]:
translate("el zumo esta en la casa")
It's also possible to loop through the keys and values of a dictionary using the items method. Let's loop through the words dictionary and see how this works:
In [ ]:
for key, value in words.items():
print(key, value)
Exercises:
Make a new py file and put that translate function in the file. Use the print function to print out some examples of using the function.
Refactor the translate function to use a list comprehension.
There are lots of ways to write that translate function. Just for fun, see if you can write the whole translate function in one line.
Note: Typing out the exercises for the next section, "Sets", is optional. If your brain is melting, feel free to sit back, relax, and enjoy the rest of the lecture.
In [ ]:
food = ("cones", 100, 3.79)
This is sometimes called packing a tuple.
In [ ]:
food
In [ ]:
type(food)
The parenthesis are often optional. They're often added for clarity. This should work too:
In [ ]:
food = "sprinkles", 10, 4.99
In [ ]:
food
Let's see what happens when we try to change our tuple:
In [ ]:
food[2] = 3
We can make an empty tuple with an empty set of parenthesis:
In [ ]:
empty = ()
In [ ]:
empty
In [ ]:
type(empty)
Any guesses how we can make a single-item tuple?
In [ ]:
food = (3)
In [ ]:
food
In [ ]:
type(food)
Python just sees this as a number with parenthesis around it. The commas are the important part. We need to add a comma after the number to make a single-item tuple:
In [ ]:
food = (3,)
In [ ]:
food
In [ ]:
type(food)
Sometimes, unpacking a tuple is also desired.
In [ ]:
yummies = [("cones", 100, 3.79), ("sprinkles", 10, 4.99), ("hot fudge", 8, 3.29), ("nuts", 6, 8.99)]
In [ ]:
yummies[2]
In [ ]:
name, amount, price = yummies[2]
In [ ]:
print("Our ice cream shop serves " + name + ".")
In [ ]:
print("The shop's inventory value for " + name + " is $" + str(amount * price) + ".")
In [ ]:
print("All this food talk is making me hungry for " + yummies[3][0] + ".")
Why not always use lists instead of tuples? Tuples use less storage space than a list. So if you are reading 1000s of small records from a file, a tuple can be an efficient way to go.
A practical learning tip: When learning a new language, there are many new terms and concepts. Sometimes it is helpful to see a bigger picture of how everything comes together. I'm a lover of "Table of Contents" since I can scan the big picture and see where something like a tuple fits in. The official Python tutorial has a very good Table of Contents, and I sometimes take 5 minutes to just click and explore something new to me.
Wow! We've come a long way today.
In [ ]: