Python – Loop Through Lists
Looping through lists is a common task in Python programming. Python provides several ways to iterate through list items using different types of loops.
Example List
fruits = ["apple", "banana", "cherry"]
1. Loop Using for
– Simple Iteration
Use a for
loop to go through each item in the list
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Best for reading or processing each item.
2. Loop Using for
with Index (range(len())
)
If you need the index of items while looping.
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(i, fruits[i])
Output:
0 apple
1 banana
2 cherry
Useful when modifying items based on index.
3. Loop Using while
You can also loop using a while
loop and an index counter.
Example:
fruits = ["apple", "banana", "cherry"]
i = 0
while i < len(fruits):
print(fruits[i])
i += 1
Output:
apple
banana
cherry
Useful in more controlled or conditional loops.
4. Loop Using enumerate()
– Get Index & Value
A cleaner way to get both index and item.
Example:
fruits = ["apple", "banana", "cherry"]
for index, value in enumerate(fruits):
print(index, value)
Output:
0 apple
1 banana
2 cherry
More Pythonic than range(len())
.
5. Loop Through Items with if
Conditions
You can filter items during looping.
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
if "a" in fruit:
print(fruit)
Output:
apple
banana
Useful for filtering or condition-based processing.
6. List Comprehension – One-Liner Loop
A Pythonic way to write loops that return new lists.
Example:
fruits = ["apple", "banana", "cherry"]
new_list = [fruit.upper() for fruit in fruits]
print(new_list)
Output:
['APPLE', 'BANANA', 'CHERRY']
Efficient and clean for transformation tasks.
Summary of Looping Methods
Method | Use Case |
---|---|
for item in list | Simple iteration |
for i in range(len()) | Need index while looping |
while loop | Conditional or custom loop logic |
enumerate() | Get both index and item |
if in loop | Filter items during iteration |
List comprehension | Fast transformation |