Python – Loop Lists
In Python, loops are used to iterate over a sequence of elements, such as lists, and perform certain actions on each item. Looping through lists is a common task in programming, as it allows you to process each element individually. In this article, we will explore different ways to loop through lists in Python, along with examples.
1. Using a for loop
The most common way to loop through a list in Python is by using a for
loop. This loop allows you to iterate over each item in the list and perform a specific action.
Here’s an example:
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
In this example, the for
loop iterates over each item in the fruits
list and assigns it to the variable fruit
. The print()
function is then used to display each fruit on a new line.
Output:
apple
banana
orange
2. Using a while loop
Another way to loop through a list is by using a while
loop. This loop will continue iterating until a certain condition is met.
Here’s an example:
fruits = ['apple', 'banana', 'orange']
index = 0
while index < len(fruits):
print(fruits[index])
index += 1
In this example, we initialize a variable index
to 0 and use it to access each item in the fruits
list. The len()
function is used to get the length of the list, and the loop continues until the index reaches the length of the list.
Output:
apple
banana
orange
3. Using list comprehensions
List comprehensions provide a concise way to loop through a list and perform operations on each item. They allow you to create a new list based on an existing list.
Here’s an example:
numbers = [1, 2, 3, 4, 5]
squared_numbers = [num ** 2 for num in numbers]
print(squared_numbers)
In this example, we use a list comprehension to create a new list called squared_numbers
. The expression num ** 2
is applied to each element in the numbers
list, and the result is added to the new list.
Output:
[1, 4, 9, 16, 25]
Conclusion
Looping through lists is a fundamental concept in Python programming. By using for
loops, while
loops, or list comprehensions, you can iterate over each item in a list and perform various operations on them. Understanding how to loop through lists is essential for manipulating data and performing repetitive tasks in Python.