Python Collections Flashcards

1
Q

TF: Lists are mutable and strings are immutable:

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

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.

A

my_list = [1, 2, 3, “Jon”, “Snow”, [5, 6]]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

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.

A

best = [1, 2, 3]

best. extend([4, 5])
best. insert(0, “start”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

TF: The + symbol is used to concatenate two lists together, just like with strings.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What does the first_list.extend(second_list) method do?

A

Adds the contents of a second list onto the first list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

letters = [“A”, “B”, “C”]
letters.append([“D”, “E”, “F”])
What will letters be at the end of this?

A

[“A”, “B”, “C”, [“D”, “E”, “F”]]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

I want my_list to have 1 as the last item.
Complete this method call:

My_list. _________ (1)

A

append

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does the list() function do?

A

Creates a new list & turns an iterable into a list.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the first argument to the .insert() method?

A

Index - the position in the list that you want something inserted

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are the 2 ways we can delete an item from the list?

alpha_list = [“A”, “B”, “C”, “D”, “E”]

A

Del
del alpha_list[2]
.remove()
alpha_list.remove(“D”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

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)

A

It will remove the first 1 in the list and keep the second. So [2, 3, 4, 1]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What happens if we try to .remove() an item that doesn’t exist in the list?

A

We get a ValueError

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What does ‘pass’ do?

A

A pass is essentially a “do nothing” statement.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

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
A
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What does .pop do?

A

.pop() will remove and return the last item from a list.

names.pop()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What do you have to use if you want to pop an item that isn’t the last one in the list?

A

.pop(index) will remove whatever index the item is at, assuming something is.
names.pop(0)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

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.

A

messy_list.pop(3)
messy_list.insert(0, 1)

messy_list.remove(“a”)
messy_list.remove(False)
messy_list.remove([1, 2, 3])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is a slice?

A

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]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What happens when you don’t provide a value for the start or end off of a slice?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

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.

A

slice1 = favorite_things[1:4]

slice2 = favorite_things[5:]

sorted_things = favorite_things[:]
sorted_things.sort()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How do you splice with a step?

A

[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.

22
Q

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].

A
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]
23
Q

a_list = [1, 2, 3]
a_list _____
Copy the entire list with a slice.

A

a_list[:]

24
Q

[1:] will stop where?

A

The end of an iterable

25
Q

TF: Slices can only be used on lists.

A

False

26
Q

[:4] will start at what index?

A

0

27
Q

How do you delete using slices? Delete Black to Aqua

rainbow = [“red”, “orange”, “green”, “yellow”, “blue”, “black”, “white”, “aqua”, “puple”, “pink”]

A

del rainbow[5:8]

28
Q

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”]

A

rainbow[2:4] = [“yellow”, “green”]

29
Q

How would you add “indigo‘ after blue using slices?

A

rainbow[4:5] = [“blue”, “indigo”]

30
Q

TF: When replacing a slice with another iterable, they must be the same size.

A

False

31
Q

What step do I want to use if I want every item in reverse?

A

-1

32
Q

grades = [70, 82, 94, 105, “B”, “A”, 72, “D”]

Given the above list, how would I delete the letter grades?

A

del grades[4:6]

del grades[-1]

33
Q

Name the three parts of the slice syntax.

[_____ : ______ : ______]

A

Start, stop, step

34
Q

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?

A

Grades[4:6] = [89. 94]

35
Q

______ my_list[2:5]

What keyword do I need to use to remove this slice from the list?

A

Del

36
Q

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, //.

A

def sillycase(word):

return word[:len(word)//2].lower() + word[len(word)//2:].upper()
37
Q

What are dictionaries?

A

Data set that is like an unordered list of keys and values.

course = {“title”: “Python Collections”}

38
Q

What happens when you search for a value using a key in a dictionary that does not exist?

A

KeyError

39
Q

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.

A

player = {“name”: “Jon snow”, “remaining_lives”: 3}

player = {“name”: “Jon snow”,
“remaining_lives”: 3,
“levels”: [1, 2, 3, 4],
“items”: {“friends”: 3} }

40
Q

What are the 2 ways that you can add an item to your dictionary?

A

Person[“last_name”] = “snow”

Or person.update({“last_name”: “Snow”})

41
Q

How do you delete something in a dictionary?

A

del person[“last_name”]

42
Q

What method is used to set or change several keys and their values at once?

A

.update()

43
Q

What types of data can be used for keys?

A

String numbers and tuples

44
Q

With the following code:
test_dict = {“a”: 1, “b”: 2, “a”: 3}
what value would test_dict[“a”] return?

A

It’ll be 3 because the keys are created in order. First it’s 1 and then the 3 is assigned later.

45
Q

TF: Dictionary keys have an order.

A

False

46
Q

Set the key color to the value ‘red’.

My_car [______ ] = _______

A

My_car[“color”] = “red”

47
Q

How do you remove a key from a dictionary?

A

Del

48
Q

What does packing a dictionary mean?

A

Putting multiple keyword arguments into a single dictionary.

> > > def packing(**kwargs):
print(len(kwargs))
packing(name=”Kenneth”)

This will print {“name”: “Kenneth”}

49
Q

What does unpacking a dictionary mean?

A

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!”

50
Q

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}!”

A
def string_factory(values):
    new_list = []
    for item in values:
        new_list.append(template.format(**item)
    return new_list
51
Q

How do you get the key, value or items of a dictionary?

A

.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.