What is a Python iterator?

What is a Python iterator?

a) An object that can be iterated upon, returning elements one at a time
b) A function that allows iteration over a sequence of values
c) A built-in function for creating loops
d) A module that provides tools for string manipulation

Answer:

a) An object that can be iterated upon, returning elements one at a time

Explanation:

A Python iterator is an object that can be iterated upon, meaning it returns elements one at a time when traversed, typically using a loop or by explicitly calling the next() method. Iterators are the foundation of Python’s iteration protocols, which allow for efficient looping over sequences and other data structures.

# Example of using an iterator
numbers = iter([1, 2, 3, 4, 5])

print(next(numbers))  # Output: 1
print(next(numbers))  # Output: 2

In this example, an iterator is created from a list, and the next() function is used to retrieve elements one by one.

Iterators are essential for Python’s iteration mechanisms, including for loops, comprehensions, and generator expressions, enabling efficient and flexible data traversal.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top