Recall & Review
beginner
What does it mean to iterate over a list in Python?
Iterating over a list means going through each item in the list one by one to perform an action with each item.
Click to reveal answer
beginner
Which Python keyword is commonly used to loop through each item in a list?
The for keyword is used to loop through each item in a list.
Click to reveal answer
beginner
What will this code print?<br>
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)It will print each fruit on its own line:<br>apple<br>banana<br>cherry
Click to reveal answer
intermediate
How can you access both the index and the item when iterating over a list?
Use the
enumerate() function in the loop, like:<br>for index, item in enumerate(my_list):
# do something with index and itemClick to reveal answer
intermediate
True or False: You can modify the items of a list directly while iterating over it.
True, but you should be careful. Modifying the list while iterating can cause unexpected behavior if you add or remove items. Changing item values is safe.
Click to reveal answer
What does the following code do?<br>
numbers = [1, 2, 3]
for num in numbers:
print(num * 2)✗ Incorrect
The loop goes through each number and prints the number multiplied by 2.
Which function helps get the index and value when looping over a list?
✗ Incorrect
The enumerate() function returns pairs of (index, value) during iteration.
What will this code print?<br>
items = ['a', 'b', 'c']
for i in range(len(items)):
print(items[i])✗ Incorrect
The loop uses indexes to access each item and prints them one by one.
Is this a correct way to loop over a list?<br>
for item in my_list:
print(item)✗ Incorrect
This is the standard way to loop through all items in a list.
What happens if you modify a list by adding items while iterating over it?
✗ Incorrect
Changing the list size during iteration can confuse the loop and cause errors or infinite loops.
Explain how to use a for loop to iterate over a list and print each item.
Think about how you would tell a friend to read each item one by one.
You got /4 concepts.
Describe how to get both the index and the value of items when looping over a list.
Remember there is a special function that helps with indexes.
You got /4 concepts.