What will print?
fruits = ["apple", "banana", "cherry"]
print(fruits[2])
cherry
You do not need .replace() to change an element in a list because lists are __________.
mutable
Explain what the following for loop is doing with list x:
for elem in x:
print(elem)
Prints each element in x on a new line.
Use this method to empty out all elements from a list.
.clear()
a = [1, 2, 3, 4]
[YOUR CODE HERE]
print(a) --> Prints [1, 2, 3, 4, 5]
a.append(5)
a = [1, 2, 3, 4]
How would you change the 4 in this list to a 5?
a[3] = 5
a = [1, 2, 3, 5]
Susan is trying to make a = [1, 2, 3, 4, 5], so she codes:
a.insert(4, 3)
The above code is flawed. What actually prints?
[1, 2, 3, 5, 3]
Explain what the following for loop is doing to list x in your own words:
for i in range(3):
x.pop(0)
It is removing the first 3 elements in the list.
Use this method to add an element to the beginning of a list.
.insert()
a = [1, 2, 3, 4]
[YOUR CODE HERE]
print(a) --> Prints [4, 3, 2, 1]
a.reverse()
How would you print the sum of the first element and last element in a list called x?
print(x[0] + x[-1])
Susan tries removing the second element from her list called y:
y = [1, 2, 3, 4, 5]
y.remove(1)
Why does her code not work as intended?
.remove() removes the value 1, not what's at index 1.
Write a for loop that allows the user to enter 5 integer values and store them in a list.
x = []
for i in range(5):
num = int(input("Enter number: ")
x.append(num)
Use this method to randomize the order of elements in a list.
random.shuffle()
f = [1, 2, 3, 4, 5]
[YOUR CODE HERE]
Prints a random element from f
print(random.choice(f))
x = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
What is the value of x[1][2]?
6
x = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
print(x[3][2])
Why does the above code error?
There is no row at index 3, so it is an IndexOutOfBoundsError.
Write a for loop that prints only the even elements from a list of integers called x.
for num in x:
if num % 2 == 0:
print(num)
What method would you use to remove the last element in a list?
.pop()
x = "1, 2, 3, 4"
[YOUR CODE HERE]
print(y) --> Prints [1, 2, 3, 4]
y = x.split(", ")
What will print?
x = [5, 3, 1, 9, 6]
print(x[2:4]*2 + x[0: 2])
[1, 9, 1, 9, 5, 3]
Susan is trying to append "dog" to her list called animals. She codes:
animals = animals.append("dog")
print(animals)
"None" prints. What did she do wrong?
She should not re-assign animals because lists are mutable.
animals.append("dog")
The following nested for loop prints each element in a 2D list called z:
for i in range(3):
for j in range(4):
print(z[i][j])
Write a nested FOR EACH loop that does the same thing.
for row in z:
for col in row:
print(col)
Use this method to combine two lists.
.extend()
m = [3, 2, 1, 5]
[YOUR CODE HERE]
[YOUR CODE HERE]
print(m) --> Prints [1, 2, 3, 4, 5]
m.sort()
m.insert(3, 4)
or similar code