Loop Through Lists
Looping through lists is a fundamental operation in Python. You can use loops to iterate over the items in a list, allowing you to perform actions on each element. The two most common loops for iterating through lists are the for
loop and the while
loop.
Using a for
Loop
The for
loop is the most common way to iterate through the elements of a list. It automatically loops through each item in the list, one by one.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry
The for
loop is straightforward and concise. It is ideal for when you want to perform an action for each item in a list.
Using a while
Loop
A while
loop can also be used to iterate through a list. This approach gives you more control over the iteration process, as it continues to loop until a specified condition is no longer true.
fruits = ["apple", "banana", "cherry"]
i = 0
while i < len(fruits):
print(fruits[i])
i += 1
# Output:
# apple
# banana
# cherry
In this example, the while
loop uses an index variable i
to access each element in the list. The loop continues until the index reaches the length of the list.
Looping with enumerate()
The enumerate()
function is useful when you need to access both the index and the value of items in the list during iteration.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
# Output:
# Index 0: apple
# Index 1: banana
# Index 2: cherry
Using enumerate()
allows you to keep track of the index of each element alongside the value, which can be helpful in many scenarios.
Looping with List Comprehension
List comprehension provides a concise way to loop through a list and apply an operation to each item, often creating a new list as a result.
fruits = ["apple", "banana", "cherry"]
# Create a new list with the length of each fruit name
lengths = [len(fruit) for fruit in fruits]
print(lengths)
# Output:
# [5, 6, 6]
This method is not only concise but also highly readable, making it a popular choice for transforming lists.
Practical Example: Filtering Lists
Suppose you want to create a new list that contains only the fruits with names longer than five characters. You can use a loop to achieve this:
fruits = ["apple", "banana", "cherry", "date"]
# Filter fruits with names longer than 5 characters
long_fruits = [fruit for fruit in fruits if len(fruit) > 5]
print(long_fruits)
# Output:
# ["banana", "cherry"]
This example demonstrates how list comprehension can be used to filter lists based on a condition.
Import Links
Here are some useful import links for further reading: