Iterating Through Lists with Built-in Functions
Python provides several built-in functions and methods that make it easy to iterate through lists. Here are some of the most commonly used ones:
for
loop
The most basic way to iterate through a list is using a for
loop:
my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)
This will output:
1
2
3
4
5
enumerate()
The enumerate()
function allows you to iterate through a list while also getting the index of each element:
my_list = ['apple', 'banana', 'cherry']
for index, item in enumerate(my_list):
print(f"Index {index}: {item}")
This will output:
Index 0: apple
Index 1: banana
Index 2: cherry
zip()
The zip()
function allows you to iterate through multiple lists simultaneously:
fruits = ['apple', 'banana', 'cherry']
prices = [0.99, 1.25, 1.50]
for fruit, price in zip(fruits, prices):
print(f"{fruit} costs {price}")
This will output:
apple costs 0.99
banana costs 1.25
cherry costs 1.50
map()
The map()
function applies a function to each element in a list:
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers)
This will output:
[1, 4, 9, 16, 25]
filter()
The filter()
function creates a new list with elements that pass a certain condition:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
This will output:
[2, 4, 6, 8, 10]
These are just a few examples of the many built-in functions and methods available in Python for iterating through lists. Understanding how to use these tools can help you write more efficient and expressive code.