Python – Loop Lists
In Python, you can loop through lists using several different methods, such as for loops, while loops, and list comprehensions. Here’s a guide to different ways of looping through lists:
1. Using a for Loop
The most common way to loop through a list is by using a for loop. This will iterate through each item in the list.
my_list = ["apple", "banana", "cherry"]
# Loop through each item in the list
for item in my_list:
print(item)
Output:
apple
banana
cherry
2. Using range() and Indexing
If you need to access both the index and the value of each item in the list, you can use the range() function to loop through indices.
my_list = ["apple", "banana", "cherry"]
# Loop through list using indices
for i in range(len(my_list)):
print(f"Index {i}: {my_list[i]}")
Output:
Index 0: apple
Index 1: banana
Index 2: cherry
3. Using enumerate() for Index and Value
The enumerate() function is a more Pythonic way to loop through a list when you need both the index and value. It returns a tuple containing the index and the item.
my_list = ["apple", "banana", "cherry"]
# Loop through list with enumerate() to get index and value
for index, item in enumerate(my_list):
print(f"Index {index}: {item}")
Output:
Index 0: apple
Index 1: banana
Index 2: cherry
4. Using while Loop
You can also use a while loop to iterate through a list. In this case, you need to manually manage the index.
my_list = ["apple", "banana", "cherry"]
# Using a while loop to iterate through the list
i = 0
while i < len(my_list):
print(my_list[i])
i += 1
Output:
apple
banana
cherry
5. Using List Comprehension
List comprehension provides a concise way to loop through a list and create a new list based on an existing one. It’s often used when you want to modify or filter the items in the list.
my_list = ["apple", "banana", "cherry"]
# Create a new list where all items are converted to uppercase
new_list = [item.upper() for item in my_list]
print(new_list)
Output:
['APPLE', 'BANANA', 'CHERRY']
6. Using map() Function
The map() function applies a specified function to each item in an iterable (like a list) and returns an iterator (which can be converted to a list).
my_list = ["apple", "banana", "cherry"]
# Use map to convert all items to uppercase
new_list = list(map(lambda x: x.upper(), my_list))
print(new_list)
Output:
['APPLE', 'BANANA', 'CHERRY']
7. Looping Through Multiple Lists Using zip()
If you have two or more lists and want to iterate over them simultaneously, you can use the zip() function. It pairs the elements of multiple iterables together.
list1 = ["apple", "banana", "cherry"]
list2 = ["orange", "grape", "pear"]
# Loop through multiple lists using zip
for item1, item2 in zip(list1, list2):
print(f"{item1} and {item2}")
Output:
apple and orange
banana and grape
cherry and pear
8. Looping Through a List in Reverse Order
You can loop through a list in reverse order using the reversed() function or by using negative indexing.
my_list = ["apple", "banana", "cherry"]
# Loop through the list in reverse using reversed()
for item in reversed(my_list):
print(item)
Output:
cherry
banana
apple
Or using negative indexing:
my_list = ["apple", "banana", "cherry"]
# Loop through the list in reverse using negative indexing
for i in range(len(my_list)-1, -1, -1):
print(my_list[i])
Output:
cherry
banana
apple
9. Using for Loop with a Conditional
You can add conditions inside the loop to filter which items you want to process.
my_list = ["apple", "banana", "cherry", "date"]
# Loop and only print items that contain the letter 'a'
for item in my_list:
if "a" in item:
print(item)
Output:
apple
banana
date
10. Nested Loops for Nested Lists
If you have a nested list (a list within a list), you can use nested loops to access each item.
nested_list = [["apple", "banana"], ["cherry", "date"], ["fig", "grape"]]
# Loop through nested list
for sublist in nested_list:
for item in sublist:
print(item)
Output:
apple
banana
cherry
date
fig
grape
Summary:
forloop: Iterate over the list directly.range()with indexing: Loop by index and access items by index.enumerate(): Get both the index and value in a clean and Pythonic way.whileloop: Loop with manual index management.- List comprehension: Concise and efficient iteration for creating new lists.
map()function: Apply a function to each item in the list.zip(): Loop through multiple lists simultaneously.reversed(): Loop in reverse order.- Conditional
forloop: Filter items during the loop. - Nested loops: Iterate through nested lists (list of lists).
These methods allow you to efficiently loop through lists in different scenarios.