0
0
Pythonprogramming~5 mins

Iterating over lists in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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 item
Click 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)
ACauses an error
BPrints 1, 2, 3 each on a new line
CPrints 2, 4, 6 each on a new line
DPrints the list [2, 4, 6]
Which function helps get the index and value when looping over a list?
Aenumerate()
Bindex()
Crange()
Dlen()
What will this code print?<br>
items = ['a', 'b', 'c']
for i in range(len(items)):
    print(items[i])
A0 1 2 on separate lines
Ba b c on separate lines
CError because of range()
DNothing
Is this a correct way to loop over a list?<br>
for item in my_list:
    print(item)
AOnly works if list has numbers
BNo, it will cause an error
COnly works if list is empty
DYes, it loops through each item
What happens if you modify a list by adding items while iterating over it?
AIt can cause unexpected behavior or an infinite loop
BThe loop will include the new items automatically
CPython prevents adding items during iteration
DNothing special happens
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.