Working with Iterator Functions
Python provides several built-in iterator functions that can be used to work with iterators more efficiently. Let's explore some of the most commonly used iterator functions.
iter()
The iter()
function is used to create an iterator from an iterable object, such as a list, string, or set.
my_list = [1, 2, 3, 4, 5]
my_iterator = iter(my_list)
print(next(my_iterator)) ## Output: 1
print(next(my_iterator)) ## Output: 2
next()
The next()
function is used to retrieve the next item from an iterator. If there are no more items, it raises a StopIteration
exception.
my_iterator = iter([10, 20, 30])
print(next(my_iterator)) ## Output: 10
print(next(my_iterator)) ## Output: 20
print(next(my_iterator)) ## Output: 30
print(next(my_iterator)) ## Raises StopIteration
zip()
The zip()
function takes one or more iterables and returns an iterator of tuples, where each tuple contains the corresponding elements from each iterable.
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")
map()
The map()
function applies a given function to each item in an iterable and returns an iterator with the transformed values.
def square(x):
return x ** 2
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
print(list(squared_numbers)) ## Output: [1, 4, 9, 16, 25]
filter()
The filter()
function creates an iterator that includes only the items from an iterable for which a given function returns True
.
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(is_even, numbers)
print(list(even_numbers)) ## Output: [2, 4, 6, 8, 10]
These are just a few examples of the many iterator functions available in Python. By understanding and using these functions, you can write more efficient and expressive code when working with iterators.