Python Iterators (Iterator Usage)
Page Info
Content
Python Iterators (Iterator Usage)
In Python, an iterator is an object that allows you to traverse through all elements of a collection (like lists, tuples, or dictionaries) one by one, without exposing the underlying structure. Iterators are implemented using the __iter__()
and __next__()
methods.
Creating and Using an Iterator
# A simple list
my_list = [10, 20, 30]
# Get an iterator from the list
it = iter(my_list)
# Access elements using next()
print(next(it)) # Output: 10
print(next(it)) # Output: 20
print(next(it)) # Output: 30
# next(it) would raise StopIteration if called again
Explanation:
iter(my_list)
: Returns an iterator object for the list.next(it)
: Returns the next element from the iterator.- StopIteration: Raised when there are no more elements to iterate.
Using Iterators in a Loop
my_list = [1, 2, 3, 4, 5]
# For loop automatically handles the iterator
for item in my_list:
print(item)
# Output: 1 2 3 4 5
Explanation:
- A
for
loop internally creates an iterator and callsnext()
until StopIteration is raised. - This is the most common way to use iterators in Python.
Creating a Custom Iterator
# Custom iterator class
class MyNumbers:
def __init__(self, max):
self.max = max
self.num = 0
def __iter__(self):
return self
def __next__(self):
if self.num < self.max:
current = self.num
self.num += 1
return current
else:
raise StopIteration
# Using the custom iterator
numbers = MyNumbers(5)
for n in numbers:
print(n)
# Output: 0 1 2 3 4
Key Points
- Iterator: An object with
__iter__()
and__next__()
methods. - iter(): Used to get an iterator from an iterable.
- next(): Used to get the next element from an iterator.
- StopIteration: Signals that iteration is complete.
- Custom iterators allow fine-grained control over how elements are generated or returned.
SEO Keywords
Python iterator example, Python next() function, Python __iter__ __next__, Python custom iterator, Python for loop iterator, Python iterable
Using iterators in Python enables efficient traversal of data collections and supports lazy evaluation, which is particularly useful for large datasets.
Good0 Bad0
댓글목록
등록된 댓글이 없습니다.