9/4/26About 1 minAbout 210 words
Concept: Iterating over lists or tuples
To iterate over a list or tuple, you can use a for .. in loop. The loop will go through each item in the collection one by one.
Lists
users = ["Alice", "Bob", "Charlie", "David"]
for user in users:
print(user, end=" ") # Output: Alice Bob Charlie DavidTuples
users = ("Alice", "Bob", "Charlie", "David")
for user in users:
print(user, end=" ") # Output: Alice Bob Charlie DavidAs the example above shows, the syntax for iterating over a list or tuple is the same. If desired, you can also use the enumerate() function to get both the index and the value of each item in the collection. This function return s a tuple containing the index and the value of each item in the collection, which can be unpacked in the for .. in loop.
Lists
users = ["Alice", "Bob", "Charlie", "David"]
for (i, user) in enumerate(users):
print(f"({i}) {user}", end=" ") # Output: (0) Alice (1) Bob (2) Charlie (3) DavidTuples
users = ("Alice", "Bob", "Charlie", "David")
for (i, user) in enumerate(users):
print(f"({i}) {user}", end=" ") # Output: (0) Alice (1) Bob (2) Charlie (3) David