Looping Through Python Lists
You can loop through the items of a list using a for loop.
Using for Loop
Example: Iterating Over a List
# Looping through a list
cities = ["New York", "London", "Paris", "Tokyo"]
for city in cities:
print("City:", city)
Output
City: New York
City: London
City: Paris
City: Tokyo
Explanation: The for loop iterates over each item in the list and prints it.
Using range() and len()
Example: Looping with Index
# Looping with index
for i in range(len(cities)):
print(f"City {i+1}: {cities[i]}")
Output
City 1: New York
City 2: London
City 3: Paris
City 4: Tokyo
Explanation: Using range() and len(), we can loop through the indices of the list and access items by their index.