Python Collections Flashcards
TF: Lists are mutable and strings are immutable:
True. When you change a list, it’s now different but it still takes up the same spot in the memory. A string however, when you change it, it takes up a new spot in memory.
This challenge is just meant as a refresher. Create a single new list variable named my_list. Put 3 numbers and 2 strings into it in whatever order you want. For the last member, though, add another list with 2 items in it.
my_list = [1, 2, 3, “Jon”, “Snow”, [5, 6]]
Create a list named best that has three items in it. The items can be anything you want.
Using .extend(), .append(), or +, add two new items onto the end of best. Again, the items can be anything you want.
Finally, use the .insert() method to place the string “start” at the beginning of your best list.
best = [1, 2, 3]
best. extend([4, 5])
best. insert(0, “start”)
TF: The + symbol is used to concatenate two lists together, just like with strings.
True
What does the first_list.extend(second_list) method do?
Adds the contents of a second list onto the first list
letters = [“A”, “B”, “C”]
letters.append([“D”, “E”, “F”])
What will letters be at the end of this?
[“A”, “B”, “C”, [“D”, “E”, “F”]]
I want my_list to have 1 as the last item.
Complete this method call:
My_list. _________ (1)
append
What does the list() function do?
Creates a new list & turns an iterable into a list.
What is the first argument to the .insert() method?
Index - the position in the list that you want something inserted
What are the 2 ways we can delete an item from the list?
alpha_list = [“A”, “B”, “C”, “D”, “E”]
Del
del alpha_list[2]
.remove()
alpha_list.remove(“D”)
If you use .remove, and there are multiple items in the list with the same name? What will happen? My_list = [1, 2, 3, 4, 1] my_list.remove(1)
It will remove the first 1 in the list and keep the second. So [2, 3, 4, 1]
What happens if we try to .remove() an item that doesn’t exist in the list?
We get a ValueError
What does ‘pass’ do?
A pass is essentially a “do nothing” statement.
OK, I need you to finish writing a function for me. The function disemvowel takes a single word as a parameter and then returns that word at the end.
I need you to make it so, inside of the function, all of the vowels (“a”, “e”, “i”, “o”, and “u”) are removed from the word. Solve this however you want, it’s totally up to you!
Oh, be sure to look for both uppercase and lowercase vowels!
def disemvowel(word): return word
def disemvowel(word): new_word = "" vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"] for letters in word: if letters not in vowels: new_word += letters return new_word
What does .pop do?
.pop() will remove and return the last item from a list.
names.pop()
What do you have to use if you want to pop an item that isn’t the last one in the list?
.pop(index) will remove whatever index the item is at, assuming something is.
names.pop(0)
Alright, my list is messy! Help me clean it up!
First, start by moving the 1 from index 3 to index 0. Try to do this in a single step by using both .pop()and .insert(). It’s OK if it takes you more than one step, though!
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]] # Your code goes below here
Great! Now use .remove() and/or del to remove the string, the boolean, and the list from inside of messy_list. When you’re done, messy_list should have only integers in it.
messy_list.pop(3)
messy_list.insert(0, 1)
messy_list.remove(“a”)
messy_list.remove(False)
messy_list.remove([1, 2, 3])
What is a slice?
A slice is a new list or string made from another list or string.
If you make a slice from a list, you get a list.
If you make a slice from a string, you get a string.
[start:stop]
Favorite_things[1:4]
What happens when you don’t provide a value for the start or end off of a slice?
Both start and stop are optional. If you leave off start, the slice will start at the beginning of the iterable. If you leave off stop, the slice will continue until the end of the iterable.
Create a new variable named slice1 that has the second, third, and fourth items from favorite_things.
favorite_things = [‘raindrops on roses’, ‘whiskers on kittens’, ‘bright copper kettles’, ‘warm woolen mittens’, ‘bright paper packages tied up with string’, ‘cream colored ponies’, ‘crisp apple strudels’]
OK, let’s do another test. Get the last two items from favorite_things and put them into slice2.
Make a copy of favorite_things and name it sorted_things.
Then use .sort() to sort sorted_things.
slice1 = favorite_things[1:4]
slice2 = favorite_things[5:]
sorted_things = favorite_things[:]
sorted_things.sort()
How do you splice with a step?
[start:stop:step]
Numbers[::2] → this will show us the entire list and skip every 2
Numbers[::-1] → this will give us the entire list, but backwards.
In this first one, create a function named first_4 that returns the first four items from whatever iterable is given to it.
OK, this second one should be pretty similar to the first. Make a new function named first_and_last_4. It’ll accept a single iterable but, this time, it’ll return the first four and last four items as a single value.
OK, try this one on for size: create a new function named odds that returns every item with an odd index in a provided iterable. For example, it would return the items at index 1, 3, and so on.
Make a function named reverse_evens that accepts a single iterable as an argument. Return every item in the iterable with an even index…in reverse.
For example, with [1, 2, 3, 4, 5] as the input, the function would return [5, 3, 1].
def first_4(list): return list[0:4]
def first_and_last_4(list): return first_4(list) + list[-4::1]
def odds(list): return list[1::2]
def reverse_evens(list): return list[::2][::-1]
a_list = [1, 2, 3]
a_list _____
Copy the entire list with a slice.
a_list[:]
[1:] will stop where?
The end of an iterable
TF: Slices can only be used on lists.
False
[:4] will start at what index?
0
How do you delete using slices? Delete Black to Aqua
rainbow = [“red”, “orange”, “green”, “yellow”, “blue”, “black”, “white”, “aqua”, “puple”, “pink”]
del rainbow[5:8]
How do you change the order of a list using slices?
Swap green and yellow
rainbow = [“red”, “orange”, “green”, “yellow”, “blue”, “black”, “white”, “aqua”, “puple”, “pink”]
rainbow[2:4] = [“yellow”, “green”]
How would you add “indigo‘ after blue using slices?
rainbow[4:5] = [“blue”, “indigo”]
TF: When replacing a slice with another iterable, they must be the same size.
False
What step do I want to use if I want every item in reverse?
-1
grades = [70, 82, 94, 105, “B”, “A”, 72, “D”]
Given the above list, how would I delete the letter grades?
del grades[4:6]
del grades[-1]
Name the three parts of the slice syntax.
[_____ : ______ : ______]
Start, stop, step
grades = [70, 82, 94, 105, “B”, “A”, 72, “D”]
Given the above list, how would I replace the middle two letter grades with 89 and 94?
Grades[4:6] = [89. 94]
______ my_list[2:5]
What keyword do I need to use to remove this slice from the list?
Del
This one will be named sillycase and it’ll take a single string as an argument.
sillycase should return the same string but the first half should be lowercased and the second half should be uppercased.
For example, with the string “Treehouse”, sillycase would return “treeHOUSE”.
Don’t worry about rounding your halves, but remember that indexes should be integers. You’ll want to use the int() function or integer division, //.
def sillycase(word):
return word[:len(word)//2].lower() + word[len(word)//2:].upper()
What are dictionaries?
Data set that is like an unordered list of keys and values.
course = {“title”: “Python Collections”}
What happens when you search for a value using a key in a dictionary that does not exist?
KeyError
Make a dictionary named player and add two keys to it. The first key should be “name” and the value can be any string you want.
The second key should be “remaining_lives”. Set this key’s value to 3.
Now add a “levels” key. It should be a list with the values 1, 2, 3, and 4 in it.
And, lastly, add an “items” key. This key’s value should be another dictionary. Give it at least one key and value, but they can be anything you want.
player = {“name”: “Jon snow”, “remaining_lives”: 3}
player = {“name”: “Jon snow”,
“remaining_lives”: 3,
“levels”: [1, 2, 3, 4],
“items”: {“friends”: 3} }
What are the 2 ways that you can add an item to your dictionary?
Person[“last_name”] = “snow”
Or person.update({“last_name”: “Snow”})
How do you delete something in a dictionary?
del person[“last_name”]
What method is used to set or change several keys and their values at once?
.update()
What types of data can be used for keys?
String numbers and tuples
With the following code:
test_dict = {“a”: 1, “b”: 2, “a”: 3}
what value would test_dict[“a”] return?
It’ll be 3 because the keys are created in order. First it’s 1 and then the 3 is assigned later.
TF: Dictionary keys have an order.
False
Set the key color to the value ‘red’.
My_car [______ ] = _______
My_car[“color”] = “red”
How do you remove a key from a dictionary?
Del
What does packing a dictionary mean?
Putting multiple keyword arguments into a single dictionary.
> > > def packing(**kwargs):
print(len(kwargs))
packing(name=”Kenneth”)
This will print {“name”: “Kenneth”}
What does unpacking a dictionary mean?
Pulling multiple keys and their values of out of a dictionary to feed them to a function.
> > > my_dict = {‘name’: ‘Kenneth’}
“Hi, my name is {name}!”.format(**my_dict)
“Hi, my name is Kenneth!”
Let’s test unpacking dictionaries in keyword arguments.
You’ve used the string .format() method before to fill in blank placeholders. If you give the placeholder a name, though, like in template below, you fill it in through keyword arguments to .format(), like this:
template.format(name=”Kenneth”, food=”tacos”)
Write a function named string_factory that accepts a list of dictionaries as an argument. Return a new list of strings made by using ** for each dictionary in the list and the template string provided.
values = [{“name”: “Michelangelo”, “food”: “PIZZA”},
{“name”: “Garfield”, “food”: “lasagna”}]
template = “Hi, I’m {name} and I love to eat {food}!”
def string_factory(values): new_list = [] for item in values: new_list.append(template.format(**item) return new_list
How do you get the key, value or items of a dictionary?
.keys() - this method returns an iterable of all of the keys in a dictionary.
.values()
- this method returns an iterable of all of the values in the dictionary.
.items()` - this method is basically a combo of the above two. It returns an iterable of key/value pairs inside of tuples.