Looping through lists is one of the most common tasks in Python. You can iterate over list items directly using a for loop, work with indexes using range() and len(), control the loop with while, or use concise list comprehensions for compact, expressive code.
for item in list_name: — best for readability when you just need the value.for i in range(len(list_name)): — use when you need both index and value.while condition: — works with a manually updated index variable.[expression for item in list_name] — creates a new list using a loop in one line.
# Define a list of fruits
fruits = ["apple", "banana", "cherry"]
# Loop through each fruit in the list
for fruit in fruits:
# Print the current fruit
print(fruit)
fruits = ["apple", "banana", "cherry"]
# Use range(len()) to loop through indexes
for i in range(len(fruits)):
# Print the index and the item at that index
print(i, fruits[i])
fruits = ["apple", "banana", "cherry"]
# Start with the first index
i = 0
# Continue looping while i is less than the list length
while i < len(fruits):
# Print the current item
print(fruits[i])
# Move to the next index
i += 1
fruits = ["apple", "banana", "cherry"]
# Print each fruit in uppercase using a list comprehension
[print(fruit.upper()) for fruit in fruits]
For the basic for loop example:
apple
banana
cherry
The loop takes each element from the fruits list in order and prints it. When using index-based loops, you also get access to the position of each element, which is useful for tasks like displaying numbered lists or modifying elements in place. List comprehensions evaluate an expression for every element and can build a new list or trigger actions for each item.
for loops for clean, readable iteration over list items.while loops when you need more complex conditions or to stop in the middle of a list.while loop to avoid infinite loops.range() boundaries to avoid off-by-one errors.for loop to print only the even numbers.for loop with range() to print list items along with their index.while loop and stop when a specific value is found.