Unit 9: Data Structures Flashcards

1
Q

What are the two types of data structures?

A

Lists and dictionaries

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

Can you add or remove items from a lists or dictionary?
Can you join 2 lists together?

A

Yes, you will learn how to add and remove items from a list or dictionary. You will also learn how to join 2 lists together and how dictionaries are different from lists.

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

What are the two other ways to store data?

A

We’ll add to our knowledge of variables with two other ways to store data: lists and dictionaries.

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

We have talked about how to store integers and strings in variables. Can you store a collection of items into just one variable?

A

Yes

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

A collection of items is called a ______

A

list

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

Code a list of friends– ( their names are Mary, Joe, Mark, and Emily) invited to a party and print them out.

A

invited_friends = [‘Mary’,’Joe’,’Mark’,’Emily’]
print(invited_friends)

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

Why are lists powerful?

A

Lists are particularly powerful because we can access each item in the list individually as well as the whole list as a group.

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

When you use computers, counting tends to start at 0, so to access the second item, we use position _____

A

“1”

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

Code a list of friends– ( their names are Mary, Joe, Mark, and Emily) invited to a party and print them out and access the second person.

A

invited_friends = [‘Mary’,’Joe’,’Mark’,’Emily’]
print(invited_friends)
print(invited_friends[1])

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

Code a list of friends– ( their names are Mary, Joe, Mark, and Emily) invited to a party and print them out and use a for loop.

A

invites_list = [‘Mary’,’Joe’, ‘Mark’, ‘Emily’]
for count in range(0,4):
print(invites_list[count])

The for loop lets us step through each item on the list and print it out. We manually set the end of our loop to 4 so that it would go through each of the positions.

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

Code a list of friends– (you do not now how many items are in our list) invited to a party and print them out.
Use a for loop.

A

Python gives us a special function to find out how many items are in a list–> len()

invites_list = [‘Mary’,’Joe’,’Mark’,’Emily’]
length = len(invites_list)
print(length)

Output:
4

We can use this variable in our for loop so that our loop always works no matter how long the list is.

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

We can use this variable–> len() in our for loop so that our loop always works no matter how long the list is. Show an example of this given this information:
invites_list = [‘Mary’,’Joe’,’Mark’,’Emily’]
length = len(invites_list)

A

invites_list = [‘Mary’,’Joe’,’Mark’,’Emily’]
length = len(invites_list)
for count in range(0,length):
print(invites_list[count])

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

What if we want to add, remove or change things in our list?

Change:
Instead of Joe coming to our party, his sister Lisa is going to come instead, so let’s change his name.

Add:
We have decided that we want to add Mandy and Carlos to our invitation list so we’re going to add their names to the end of our list.

Remove:
Mark can’t make it for the party.

A

Changing things–> just like you can access the items in the list with the bracket notation, we can change things in the list with it.

invites_list = [‘Mary’,’Joe’,’Mark’,’Emily’]
print(invites_list[1])
invites_list[1] = “Lisa”
print(invites_list[1])

Output:
Joe
Lisa

We add items to a list after we created it using append()
invites_list = [‘Mary’,’Joe’,’Mark’,’Emily’]
invites_list.append(“Mandy”)
invites_list.append(“Carlos”)
print(invites_list)

Remove:
we use the del command to remove an item.
We need to know what position it is for it to work. Mark is item 2, in the third position in the list.
invites_list = [‘Mary’,’Joe’,’Mark’,’Emily’]
invites_list.append(“Mandy”)
invites_list.append(“Carlos”)
del invites_list[2]
print(invites_list)

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

How do you add lists together?
Refer to this example and think about how you can add lists together.

invites_list = [‘Mary’,’Joe’,’Mark’,’Emily’]
invites_list.append(“Mandy”)
invites_list.append(“Carlos”)
del invites_list[2]
more_invites = [“Sherry”, “Michael”, “Nick”]
print(more_invites)

A

We can use the + sign to add the two lists together.
We can either assign it to the same list variable or to a new one.

New one:
invites_list = [‘Mary’,’Joe’,’Mark’,’Emily’]
invites_list.append(“Mandy”)
invites_list.append(“Carlos”)
del invites_list[2]
more_invites = [“Sherry”, “Michael”, “Nick”]
full_invite_list = invites_list + more_invites
print(full_invite_list)

Adding the new items to one of our original list variables:
invites_list = [‘Mary’,’Joe’,’Mark’,’Emily’]
invites_list.append(“Mandy”)
invites_list.append(“Carlos”)
del invites_list[2]
more_invites = [“Sherry”, “Michael”, “Nick”]
invites_list = invites_list + more_invites
print(invites_list)

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

We are going to create a list of test scores. Jake got a 93 on the first test, an 87 on the second test, and a 98 on the third test.
Let’s create a list on the scores and use a for loop to calculate the average of our four test scores.

Then, Jake’s teacher let him retake the fourth test and he got a 92 on the retake. Let’s change that test score and then calculate the average again.

Finally, Jake’s teacher decided not to include the third test score in his final grade. Now we need to remove it and check his average again.

A

We will use the len() function to find out how many test scores there are so that we can use this code again if we need to do so.

test_scores = [93,87,98]

def calculate_average(scores):
total = 0
number_of_scores = len(scores)
for count in range(0, number_of_scores):
total = total + scores[count]
average = total/ number_of_scores
return average
test_scores[3] = 92
del(test_scores[2])
print(calculate_average(test_scores))

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

Drag and drop each line of code in the program to complete the following:

Create a list of items containing 7 programming languages.
“Ada”
“Basic”
“C”
“C++”
“Java”
“Python”
“Scratch”
Display the list using the print function.
Print the first item in the list.
Print the last item in the list.
Print the length of the list.
Print the last item in the list using the len() function.
Print all items in the list using a for loop.
Add a new programming language, “Smalltalk” to the end and print the updated list.
Remove the language “Basic” and print the updated list.

A

Print the last item

programming_langs = [‘Ada’,’Basic’, ‘C’, ‘C++’,’Java’,’Python’, ‘Scratch’]

print(programming_langs)
# Print the first item
print(programming_langs[0])
#Print the last item
print(programming_llangs[6])
# Print the length of list
print(len(programming_langs))
# Print the last item using length function
print(programming_langs[len(programming_langs)-1])
# Print all items using a for loop
for i in range(0,len(programming_langs)):
print(programming_langs[i])
# Add new language to the list and print result
programming_langs.append(“Smalltalk”)
print(programming_langs)
# Remove the language Basic and print result
del programming_langs[1]
print(programming_langs)

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

Activity: Continuing our list of programming langs
Drag and drop each line of code in the program to complete the following:

Create a list of items containing 7 programming languages.
“Ada”
“Basic”
“C”
“C++”
“Java”
“Python”
“Scratch”
Create a list of containing 3 programming languages.
“C#”
“Cobol”
“Fortran”
Add the 2 lists together, store this new list in programming_langs and print the result.
Sort the new list using the sort() method and print result. Note that sort() sorts the items of a list in ascending order. Unlike append() or insert(), the sort() method does not take any arguments.

A

Create the list of 7 items

programming_langs = [‘Ada’,’Basic’, ‘C’, ‘C++’, ‘Java’, ‘Python’, ‘Scratch’]

more_langs = [‘C#’,’Cobol’, ‘Fortran’]

programming_langs = programming_langs + more_langs
print(programming_langs)

programming_langs.sort()
print(programming_langs)

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

What does sort() do?

A

sort() sorts the items of a list in ascending order. Unlike append() or insert(), the sort() method does not take any arguments.

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

As we learned in previous units, when we’re Inside a loop, we iterate over a block of code for a specific number of times or until the test expression is false. However, sometimes we wish to end, or terminate the loop early or don’t want to execute the rest of the loop body for the current iteration for a specific condition within the loop. What do we use in those cases when we want to explicitly control the flow of the loop?

A

break and continue statements

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

What is the break statements used for?

A

The break statement is used when we want to stop a loop before it would normally stop. The break ends the iteration of the loop and moves the control flow to the next line of code immediately after the loop body. You can check the flowchart in CTY

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

If the break statement is inside a nested loop (loop inside another loop), the break will _________

A

the break will end only the innermost loop.

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

Let’s take a look at how this might be useful when looping through the items of a list. Say you have a list of fruits and you’re checking whether “banana” is inside the loop. If you find it, you are finished and there is no need to continue searching through the list. You should then use the _______ to terminate your search.

A

break statement.
break with lists.

my_fruits_list = [‘Apple’, ‘Banana’, ‘Orange’, ‘Mango’, ‘Berry’]
for fruits in my_fruits_list:
if fruits == ‘Banana’:
print(“Found banana. No need to search anymore”)
break
print(fruits)
print(“Out of the loop”)

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

my_fruits_list = [‘Apple’, ‘Banana’, ‘Orange’, ‘Mango’, ‘Berry’]
for fruits in my_fruits_list:
if fruits == ‘Banana’:
print(“Found banana. No need to search anymore”)
break
print(fruits)
print(“Out of the loop”)

What is the output of this?

A

The output is:
Apple
Found banana. No need to search anymore
Out of the loop

Explanation:
The for loop iterates through each item in my_fruits_list.
On each iteration:
It checks if the current fruit (fruits) is “Banana”.
If true, it executes the block under the if statement, prints “Found banana. No need to search anymore”, and breaks out of the loop. No further iterations occur.
If false, it skips the if block and proceeds to the print(fruits) statement, printing the fruit name.
What Happens When the Break Is Executed:
When “Banana” is found, the break statement terminates the loop immediately. The code skips the remaining fruits (‘Orange’, ‘Mango’, ‘Berry’) and proceeds to the next statement after the loop: print(“Out of the loop”).

23
Q

What is the continue statement used for?

A

continue statement
continue is used to skip the rest of the code inside a loop for the current iteration, but only if a certain condition is true. The loop does not terminate but continues or skips straight to the next iteration. You can check the flowchart in CTY

24
Q

my_fruits_list = [‘Apple’, ‘Banana’, ‘Orange’, ‘Mango’, ‘Berry’]
for fruits in my_fruits_list:
if fruits == ‘Banana’:
continue
print(fruits)
print(“Out of the loop”)

What is the output of this?

A

The output is:
Apple
Orange
Mango
Berry
Out of the loop

What Happens in Each Iteration:
fruits = ‘Apple’

Condition fruits == ‘Banana’ is false.
Prints Apple.
fruits = ‘Banana’

Condition fruits == ‘Banana’ is true.
continue skips the print(fruits) statement.
Nothing is printed for ‘Banana’.
fruits = ‘Orange’

Condition fruits == ‘Banana’ is false.
Prints Orange.
fruits = ‘Mango’

Condition fruits == ‘Banana’ is false.
Prints Mango.
fruits = ‘Berry’

Condition fruits == ‘Banana’ is false.
Prints Berry.
After the loop ends:

Prints Out of the loop.

25
Q

Drag and drop each line of code in the program to complete the following:

Create a list of items containing 7 programming languages.
“Ada”
“Basic”
“C”
“C++”
“Java”
“Python”
“Scratch”
Using a loop, print each item in the list until “Python” is found. When found, print a message and stop the search immediately.
Print a message when the loop has ended.

A

Create the list of 7 items

programming_langs = [‘Ada’,’Basic’,’C’,’C++’,’Java’,’Python’,’Scratch’]
#Loop though list
for lang in programming_langs:
#Search for ‘Python’. If found, print message and exit loop.
if lang == ‘Python’:
print(“Found Python in the list. The search is over!”)
break

#Print item
  print(lang) #Out of loop print("Now out of the loop")
26
Q

Can you create a dictionary in Python to store and manipulate a collection of key/value data pairs?

A

Yes

27
Q

Can we print a dictionary and search through a dictionary for a specific key?

A

Yes

28
Q

What are dictionaries?

A

A special way to store information in an organised fashion.

29
Q

A dictionary can also be called a _____

A

“dict”

30
Q

Each item in a dictionary has a ___ and a _____

A

a key and a value

31
Q

Let’s go back to our invitation list from a previous lecture and put the names in a table with whether or not they can come to the party, called an (RSVP).
Name (Key) RSVP(value)
Mary yes
Joe yes
Mark no
Emily yes
We could try to store this information in a list with the names, but it would not be very easy to keep track of and it would make referencing that information more difficult.
What should we do and how can we code that?
What if we wanted to check what Joe’s RSVP was?
We then decide to invite Mandy and Carlos. Mandy can come but Carlos can’t.

Finally, we remembered that Emily is out of town during the party.

A

We are going to construct a dictionary with the information. The names will be the keys and the RSVPs will be the values.

rsvps = {“Mary” : “yes”, “Joe”: “yes”, “Mark” : “no”, “Emily” : “yes”}
print(rsvps)
#We can assess Joe’s RSVP by accessing it using the key which is “Joe”.
print(rsvps[“Joe”])
#Add them to our dictionary. All we do to add them is add a new key with their names.
rsvps[“Mandy”] = “yes”
rsvps[“Carlos”] = “no”
print(rsvps)
#Let’s remove Emily from the dictionary.
del (rsvps[“Emily”])
print(rsvps)
Output:
{“Mary” : “yes”, “Joe”: “yes”, “Mark” : “no”, “Emily” : “yes”, “Mandy” : “yes”, “Carlos” : “no”}

We can assess Joe’s RSVP by accessing it using the key which is “Joe”.

32
Q

What are the few things to note about constructing a dictionary?

A

The definition of a dictionary is surrounded by curly braces like this {} instead of brackets like lists.

Each set of keys and values is separated by a comma and the key and the value are separated by a colon.

33
Q

What is the difference between lists and dictionaries?

A

Unlike lists, you can’t use the + sign to combine two different maps together for a dictionary. Python will give you an error.

34
Q

Even though dictionaries have keys that aren’t numerical like lists, _______

A

you can still lop through them using the following code:

for name, rsvp in rsvps.items():
print(“Name: “ + name)
print(“RSVP: “ + rsvp)
print(“—”)

Output:
Name: Mary
RSVP: yes

Name: Joe
RSVP: yes

Name: Mark
RSVP: no

Name: Mandy
RSVP: no

Name: Carlos
RSVP: no

35
Q

Can you run a loop in a dictionary?

A

Yes

36
Q

How do you run a loop in a dictionary?

A

for key, value in dictionary.items()
print(key)
print(value)

The word “key” in line one and two is where you will reference the keys in your dictionary. Remember, the keys in our dictionary in one of the tutorial’s example are the names, so we’re giving them an informative variable called “name”

The word “value” in line one and two is where you will reference the values in your dictionary. We named them “rsvp” in one of the tutorial’s example since that’s what our values are in this dictionary.

Finally, the word “dictionary” in line one is where you put the name of your dictionary.

37
Q

We’re going to store address information for someone. Here’s a table to show what we need to put in our dictionary.
Key Value
Address 123 Main St.
City Baltimore
State MD
Zip Code 12345

Code your dictionary. Then try printing out the address formatted like an address so that we can use it in the future as we make changes to our dictionary, we’ll turn it into a function.

We’ve learnt that the address was not quite right, so let’s update that to “456 First Street” instead.

Now, we’ve decided that we want to store a phone number too, so let’s add a key and a value for that.

A

address = {“address”: “123 Main Street”, “city” : “Baltimore”, “state” : “MD”, “Zip Code” : “12345”}
def print_address(address):
print(address [“address”])
print(address[“city”] + “, “ + address[“state”] + “ “ + str(address[“zip”]))
print_address(address)

Output:
123 Main Street
Baltimore, MD 12345

We’ve learnt that the address was not quite right, so let’s update that to “456 First Street” instead.
address = {“address”: “123 Main Street”, “city” : “Baltimore”, “state” : “MD”, “Zip Code” : “12345”}
def print_address(address):
print(address [“address”])
print(address[“city”] + “, “ + address[“state”] + “ “ + str(address[“zip”]))

address[“address”] = “456 First Street”
print_address(address)

Output:
456 First Street
Baltimore, MD 12345

Now, we’ve decided that we want to store a phone number too, so let’s add a key and a value for that.
address = {“address”: “123 Main Street”, “city” : “Baltimore”, “state” : “MD”, “Zip Code” : “12345”}
def print_address(address):
print(address [“address”])
print(address[“city”] + “, “ + address[“state”] + “ “ + str(address[“zip”]))

address[“address”] = “456 First Street”
address[“phone”] = 1234567890
print(address)

Output:
{“address”: “123 Main Street”, “city” : “Baltimore”, “state” : “MD”, “Zip Code” : 12345, “phone” : 1234567890}

38
Q

Activity: Dictionary of airports

Drag and drop each line of code in the program to complete the following:

Create a dictionary containing 5 key/value pairs of airports, where key = airport code and value = airport name.

Display the dictionary using the print function.

Print the length of the dictionary.

Print the name of the airport with code = ‘LHR’

Update “Moscow Metropolitan Area, Russia” to the airport name “Moscow International Airport, Russia” and print the updated dictionary.

Delete the “Narita International, Japan” airport and print the updated dictionary.

Add a new airport, code = ‘LAX’ and name = ‘Los Angeles International Airport, USA’ and print the updated dictionary.

Airport Dictionary
Airport Code Airport Name
IAD Washington Dulles International, USA
LHR London Heathrow, UK
NRT Narita International, Japan
MOW Moscow Metropolitan Area, Russia
SYD Sydney International Airport, Australia

A

Create the dictionary

airports = {‘IAD’ : ‘Washington Dulles Internatonal, USA’, ‘LHR’ : ‘London Heathrow, UK’ , ‘NRT’ : ‘Narita International, Japan’, ‘MOW’ : ‘Moscow Metropolitan Area, Russia’, ‘SYD’ : ‘Sydney International Airport’}

print(airports)
#Print the length of the dictionary
print(len(airports))
#Print the airport with code LHR
print(airports[‘LHR’])
#Update Russia’s airport and print updated dictionary.
airports[‘MOW’] = ‘Moscow International Airport, Russia’
print(airports)
#Delete Japan’s airport and print updated dictionary.
del airports[“NRT”]
print(airports)
#Add Los Angeles airport and print update dictionary.
airports[‘LAX’] = ‘Los Angeles International Airport, USA’
print(airports)

39
Q

Activity: Searching for airports
Drag and drop each line of code in the program to complete the following:

Create a dictionary containing 5 key/value pairs of airports, where key = airport code and value = airport name.
Print all of the airport codes and names using a for loop.
Write a function that uses a for loop and if condition to search for a specific airport code. If it’s found, print the airport name. Otherwise, print “Airport <code> not found."
Call the function to search for 'LHR' and 'YYC' in the dictionary.</code>

Airport Dictionary
Airport Code Airport Name
IAD Washington Dulles International, USA
LHR London Heathrow, UK
NRT Narita International, Japan
MOW Moscow Metropolitan Area, Russia
SYD Sydney International Airport, Australia

A

Create the dictionary

airports = {‘IAD’ : ‘ Washington Dulles International, USA’, ‘LHR’ : ‘London Heathrow, UK’ , ‘NRT’ : ‘Narita International Japan’ , ‘MOW’ : ‘Moscow Metropolitan Area, Russia’ , ‘SYD’ : ‘Sydney International Airport’}

for key, value in airports.items():
print(key, value)

def search_airport(search_key):

for key, value in airports.items():

#Check if matching airport is found
if key == search_key:

   #Print airport name and return 
          print(airports[search_key])
          return

print(‘Airport{} not found’.format(search_key))

return

search_airport(‘LHR’)
search_airport(‘YYC’)

40
Q

What is a list?

A

A List is used to store multiple items in a single variable and is created by placing elements inside square brackets.

41
Q

Let’s look at some syntax errors and runtime errors that often occur when using Lists in your programs.

In the code below, we are trying to print the last item in the list, which is ‘Emily’:

invites_list = [‘Mary’, ‘Joe’, ‘Mark’, ‘Emily’]
print(invites_list(3))
What is wrong with this code?

A

When we run this code, we get the following syntax error:

Traceback (most recent call last):
File “C:/Users/96C32572223744/Desktop/test.py”, line 2, in <module>
print(invites_list(3))
TypeError: 'list' object is not callable
Can you figure out what went wrong? We got a TypeError – ‘list is not callable’. The code is trying to access the 3rd element of the list using parentheses "(3)" instead of square brackets "[3]."Here is the corrected code, using "[]":</module>

invites_list = [‘Mary’, ‘Joe’, ‘Mark’, ‘Emily’]
print(invites_list[3])
*TIP: Remember that Python uses square brackets to enclose a list index.

42
Q

Consider the following code:

invites_list = [‘Mary’, ‘Joe’, ‘Mark’, ‘Emily’]
print(invites_list[4])
When we run this code, we get the following output:

Traceback (most recent call last):
File “C:/Users/96C32572223744/Desktop/test.py”, line 2, in <module>
print(invites_list[4])
IndexError: list index out of range</module>

What is wrong with this code?

A

This runtime error is commonly encountered when working with lists is ‘list index out of range’ error.

Remember that a list index in Python starts counting from 0 and not 1. In the example above, invites_list has 4 items (or elements), with indexes in the range of 0 to 3. The first element ‘Mary’ is invites_list[0], and the last element ‘Emily’ is at invites_list[3]. The corrected code is:

invites_list = [‘Mary’, ‘Joe’, ‘Mark’, ‘Emily’]
print(invites_list[3])
*TIP: Remember that the list index in Python starts counting at 0 and not 1.

43
Q

Let’s look at the following example where we are trying to use a “for” loop to print out every element in the list:

my_list = [“apple”, “orange”, “banana”, “strawberry”]
for i in range(0, len(my_list) - 1):
print(my_list[i])
Here is the resulting output:

apple
orange
banana

What is wrong with this code and why?

A

An IndexError occurs when you iterate a list using a “for” loop.

No error occured, but we didn’t get the results that we expected. The original list contains four items, but we only get 3 items printed out. In this program, the “for” loop goes from a range of 0 to len(my_list) - 1 and we miss the last item. We should not subtract 1 from len(my_list). The correct code is as follows:

my_list = [“apple”, “orange”, “banana”, “strawberry”]
for i in range(0, len(my_list)):
print(my_list[i])
*TIP: When using a for loop to iterate a list, use a range of (0, len(my_list)) to access every element.

44
Q

Let’s take the following example:

rsvps = {“Mary” : “yes”, “Joe” : “yes”, “Mark” : “no”, “Emily” : “yes”}
print(rsvps[‘Mary’])
print(rsvps[‘Mandy’])
When we run this code, we get the following output:

yes
Traceback (most recent call last):
File “C:/Users/96C32572223744/Desktop/test.py”, line 3, in <module>
print(rsvps['Mandy'])
KeyError: 'Mandy'</module>

A

This is a common error when using dictionaries—> ‘Key error’. This error occurs when we try to access a key that does not exist in a dictionary.

Can you figure out what is going on here? The value related to the ‘Mary’ key in the dictionary -> ‘yes’ is printed, but then an error is thrown with the second print statement. Python raises a KeyError. In this case the key ‘Mandy’ doesn’t exist in the ‘rsvps’ dictionary. One way to fix this is to remove any references to a key that doesn’t exist in the dictionary:

rsvps = {“Mary” : “yes”, “Joe” : “yes”, “Mark” : “no”, “Emily” : “yes”}
print(rsvps[‘Mary’])
The second way to fix this would be to add the missing key to the dictionary as shown below:

rsvps = {“Mary” : “yes”, “Joe” : “yes”, “Mark” : “no”, “Emily” : “yes”, “Mandy” : “yes”, }
print(rsvps[‘Mary’])
print(rsvps[‘Mandy’])
*TIP: Always be sure that the KEY exists before referencing it.

45
Q

Consider the following code:

rsvps = {“Mary” : “yes”, “Joe” : “yes”, “Mark” : “no”, “Emily” : “yes”, “Mandy” : “yes”, }
del rsvps
print(rsvps)

A

This is a common error –> trying to access a dictionary after deleting it.

We are trying to print a dictionary that does not exist and therefore, Python will throw an error as shown below:

Traceback (most recent call last):
File “C:/Users/96C32572223744/Desktop/test.py”, line 3, in <module>
print(rsvps)
NameError: name 'rsvps' is not defined
The original intent of the program was to empty the dictionary by removing all the items, and not delete it. The ‘clear()’ method should be used to remove all items from a given dictionary and return an empty dictionary, as shown below:</module>

rsvps = {“Mary” : “yes”, “Joe” : “yes”, “Mark” : “no”, “Emily” : “yes”, “Mandy” : “no”, }
rsvps.clear()
print(rsvps)
Running this code will result in an empty dictionary and the output will be as shown below:

{}
*TIP: If you want to delete the items in the dictionary, remember to use clear() method and not the “del” keyword.

46
Q

What are the five summary points for Unit 9?

A

Summary
A list index starts with 0.
Always use square brackets to enclose the index.
When using a for loop to iterate a list, remember to use a range of 0 to len(list).
Make sure that a dictionary key exists before accessing its value.
Use clear() method to empty a dictionary and del method to completely delete the dictionary.
That is all. Happy Debugging!

47
Q

Which of the following determines the number of loop iterations?

primes = [2, 3, 5, 7, 11]
for num in primes:
    print('{} is a prime number'.format(num)) Question 1Select one:

a.
for

b.
primes

c.
{}

d.
num

A

The number of loop iterations is determined by the number of elements in the list primes.

Explanation:
The for loop iterates over each element in the primes list.
The loop will execute once for each element in the list. Therefore, the number of iterations is equal to the length of the primes list.
Correct answer:
b. primes

This is because the loop iterates through each element in the primes list.

48
Q

Which of the following are true about dictionaries?

*Choose all that apply.

Question 2Select one or more:

a.
Dictionaries are also known as tuples.

b.
Once created, a dictionary cannot be changed.

c.
Each item in a dictionary has a key and corresponding value.

d.
You can loop through a dictionary using items().

e.
A dictionary is a type of data structure.

f.
Dictionaries can only contain strings.

g.
You can add dictionaries together, just like numbers.

A

Correct answers:
c. Each item in a dictionary has a key and corresponding value.

A dictionary is a collection of key-value pairs.
d. You can loop through a dictionary using items().

The .items() method allows you to iterate over both the keys and values in a dictionary.
e. A dictionary is a type of data structure.

Dictionaries are a built-in data structure in Python, used to store data in key-value pairs.
Incorrect answers:
a. Dictionaries are also known as tuples.

Incorrect: Dictionaries and tuples are different data types in Python. Dictionaries are key-value pairs, while tuples are immutable ordered sequences.
b. Once created, a dictionary cannot be changed.

Incorrect: Dictionaries are mutable, meaning you can add, update, or remove items.
f. Dictionaries can only contain strings.

Incorrect: Dictionaries can have keys and values of any data type, including strings, numbers, tuples, and even other dictionaries.
g. You can add dictionaries together, just like numbers.

Incorrect: You cannot directly add dictionaries together. However, you can merge them using methods like update() or dictionary unpacking in Python 3.9+ (dict1 | dict2).
Summary:
The correct answers are c, d, and e.

49
Q

Each item in a dictionary has which of the following?

Question 3Select one:

a.
a variable and a constant

b.
a key and a value

c.
a parent and a child

d.
an index and a list

A

Correct Answer: b. a key and a value

Each item in a dictionary is a key-value pair, where the key identifies the item, and the value is the data associated with that key.

50
Q

Which of the following is true about lists?

*Choose all that apply.

Question 4Select one or more:

a.
Once created, a list cannot be changed.

b.
You can add lists together, just like numbers.

c.
Each item in a list has a key and corresponding value.

d.
You can loop through a list using range() and len().

e.
A list may only include strings.

f.
A list is a type of data structure.

g.
Lists are also known as tuples.

A

Correct Answers:
d. You can loop through a list using range() and len().

Using range(len(list)), you can loop through a list by index.
f. A list is a type of data structure.

Lists are one of the fundamental data structures in Python for storing ordered, mutable collections.
Incorrect Options:

a. Once created, a list cannot be changed: Lists are mutable, meaning their elements can be changed, added, or removed.
b. You can add lists together, just like numbers: Lists can be concatenated using the + operator, but this does not work like numeric addition.
c. Each item in a list has a key and corresponding value: Lists do not have keys; only dictionaries do.
e. A list may only include strings: Lists can include elements of any data type.
g. Lists are also known as tuples: Lists and tuples are different data types in Python.

51
Q

Fill in the blanks.

Every item in a list has its own position called the __________ . For the first item of any list, this value is __________ .

Question 5Select one:

a.
offset, one

b.
index, zero

c.
coordinate, one

d.
item number, zero

A

Correct Answer:
b. index, zero

Each item in a list has an index, starting from 0 for the first item.

52
Q

Consider the code snippet below that creates a dictionary of Capitals, where the key is a country name and the value is the corresponding capital city:

capitals = {“USA”: “Washington, DC”,
“UK”: “London”,
“Russia”: “Moscow”,
“China”: “Beijing”
}
Which of the following will correctly print the capital city of the UK?

Question 6Select one:

a.
print(capitals[1])

b.
print(capitals[2])

c.
print(capitals[“UK”])

d.
print(capitals(“UK”))

A

Correct Answer:
c. print(capitals[“UK”])

Use square brackets to access a dictionary value by its key. The other options are incorrect syntax.

53
Q

Consider the following code:

          movie_list = ["Batman", "Spiderman", "Superman", "Jungle Book", "Harry Potter"] Which of the following correctly adds "Toy Story" and "Frozen" to movie_list?

Question 7Select one:

a.
movie_list.add(“Toy Story”, “Frozen”)

b.
movie_list.add(“Toy Story”)
movie_list.add(“Frozen”)

c.
movie_list.append(“Toy Story”, “Frozen”)

d.
movie_list.append(“Toy Story”)
movie_list.append(“Frozen”)

A

Correct Answer:
d. movie_list.append(“Toy Story”)
movie_list.append(“Frozen”)

The append() method adds a single item to the end of the list. Adding multiple items requires calling append() separately for each one.
Incorrect Options:

a, b: There is no add() method for lists.
c: append() does not accept multiple arguments. Use extend() if adding multiple items at once.

54
Q

A list named my_list has a number of items in it. Which is the correct statement to print the last item in my_list?

Question 8Select one:

a.
print(my_list[last])

b.
print(len(my_list))

c.
print(my_list[len(my_list)])

d.
print(my_list[len(my_list)-1])

A

Correct Answer:
d. print(my_list[len(my_list)-1])

The last item’s index is len(my_list) - 1, as indexing starts at 0.
Incorrect Options:

a. print(my_list[last]): last is not defined.
b. print(len(my_list)): This prints the number of items in the list, not the last item.
c. print(my_list[len(my_list)]): This results in an error because len(my_list) is out of bounds for the index.

55
Q

Consider the code below that creates a dictionary containing test credit card information:

credit_card = {‘number’ : ‘4242424242424242’,
‘expiry’ : ‘12/34’,
‘cvc’ : 123
}
Which of the following correctly updates the ‘expiry’ value to ‘12/36’?

Question 9Answer

a.
credit_card[‘expiry’] = ‘12/36’

b.
credit_card[1] = ‘12/36’

c.
credit_card{‘expiry’} = ‘12/36’

d.
none of these choices are correct.

A

Correct Answer:
a. credit_card[‘expiry’] = ‘12/36’

Use square brackets with the key to update the value in a dictionary.
Incorrect Options:

b: Dictionary keys are not indexed numerically.
c: Incorrect syntax for accessing dictionary elements.
d: Option a is correct, so this is incorrect.

56
Q

What is the output of the following code snippet?

movie_list = [“Batman”, “Spiderman”, “Superman”, “Jungle Book”, “Harry Potter”]
print(movie_list[3])
Question 10Select one:

a.
Superman

b.
Spiderman

c.
Jungle Book

d.
It displays an error message.

A

Correct Answer:
c. Jungle Book

movie_list[3] accesses the fourth element in the list (index starts at 0).
Incorrect Options:

a, b: These refer to other elements.
d: The code does not throw an error; it correctly accesses the fourth element.