Using a for loop
Using a for
loop is the most common approach to iterating through a list in Python. You can access each element individually and perform operations on them as needed.
Example:
# Creating a list
my_list = ["dog", "cat", "rabbit", "parrot", "turtle"]
# Iterating over the list using a for loop
for item in my_list:
# print each item in uppercase
print(item.upper())
Output:
DOG
CAT
RABBIT
PARROT
TURTLE
Using the enumerate() function
The Python built-in enumerate()
function provides a way to iterate over a list while also tracking the index of each element.
Example:
# Creating a list
fiction_creatures = ["ghost", "goblin", "ghoul", "zombie", "devil", "vampire"]
# Iterating over the list using enumerate()
for index, item in enumerate(fiction_creatures):
# Print index and value of each element
print(f"Index: {index}, Value: {item}")
Output:
Index: 0, Value: ghost
Index: 1, Value: goblin
Index: 2, Value: ghoul
Index: 3, Value: zombie
Index: 4, Value: devil
Index: 5, Value: vampire
Using a for loop and the range() function
Besides the enumerate()
function mentioned in the previous section, you can use this technique to access both list elements and their indices:
- Use the
range()
function to generate indices corresponding to the list length (returned by thelen()
function). - Use a
for
loop to iterate over the range of indices. - Access each element using its index within the loop.
Example:
# Creating a list
my_list = ['Python', 'JavaScript', 'FastAPI', 'Sling Academy']
# Get the length of the list
length = len(my_list)
# Iterating over the list using a for loop and range()
for i in range(length):
item = my_list[i] # Accessing each element using its index
print(item) # Print each element
Output:
Python
JavaScript
FastAPI
Sling Academy
Using a while loop
A while
loop can be used to iterate over a list by incrementing a counter until reaching the list length. It provides flexibility in controlling the loop flow but requires a little additional code.
Example:
# Creating a list
games = ["Elden Ring", "CS:GO", "Dota 2", "League of Legends", "Valorant", "Diablo 4"]
# Iterating over the list using a while loop
counter = 0
while counter < len(games):
item = games[counter] # Accessing each element using the counter
print(item) # Print each element
counter += 1 # Increment the counter
Output:
Elden Ring
CS:GO
Dota 2
League of Legends
Valorant
Diablo 4
Using list comprehension
List comprehension is a syntactic construct that allows you to create a new list based on an existing list or another iterable object, using a concise and expressive syntax. Python is one of the few programming languages that support this beautiful syntax (Haskell, C#, Ruby).
Example:
origial_list = ['one', 'two', 'three', 'four', 'five']
# create a new list with uppercase items
new_list = [item.upper() for item in origial_list]
print(new_list)
Output:
['ONE', 'TWO', 'THREE', 'FOUR', 'FIVE']
Using a high-order function
High-order functions like map()
and filter()
can be used to iterate over a list while applying transformations or filtering based on a condition.
Example of using the map()
function:
# Creating a list of numbers
numbers = [1, 2, 3, 4, 5]
# Using map() to square each number
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers)
Output:
[1, 4, 9, 16, 25]
Example of using the filter()
function:
# Creating a list of numbers
numbers = [1, 2, 3, 4, 5]
# Using filter() to select even numbers
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
Output:
[2, 4]