Python Tutorial
Python Flow Control
Python Functions
Python Data Types
Python Date and Time
Python Files
Python String
Python List
Python Dictionary
Python Variable
Python Input/Output
Python Exceptions
Python Advanced
In this Python Iterators tutorial, we'll cover the basics of iterators and how to work with them. We'll focus on the following topics:
iter()
and next()
An iterator is an object that implements the iterator protocol, which consists of the methods __iter__()
and __next__()
. Iterators are used to iterate over a collection of items, such as a list or a tuple. They provide a convenient way to loop through the elements of a collection without needing to know its internal structure.
Python's built-in data structures, like lists, tuples, sets, and dictionaries, are iterable objects. This means they can be used with an iterator. Here's an example using a list:
my_list = [1, 2, 3, 4, 5] # Create an iterator from the list my_iterator = iter(my_list) # Use the iterator to get the next value print(next(my_iterator)) # Output: 1 print(next(my_iterator)) # Output: 2
iter()
and next()
The iter()
function is used to create an iterator from an iterable object, while the next()
function is used to retrieve the next value from the iterator. If there are no more items to return, next()
raises the StopIteration
exception.
Example:
my_list = [1, 2, 3, 4, 5] my_iterator = iter(my_list) print(next(my_iterator)) # Output: 1 print(next(my_iterator)) # Output: 2 print(next(my_iterator)) # Output: 3 print(next(my_iterator)) # Output: 4 print(next(my_iterator)) # Output: 5 print(next(my_iterator)) # Raises StopIteration
A more convenient way to loop over an iterator is to use a for
loop. The loop automatically handles the StopIteration
exception and terminates when there are no more items.
Example:
my_list = [1, 2, 3, 4, 5] for value in my_list: print(value)
Output:
1 2 3 4 5
To create a custom iterator, define a class that implements the __iter__()
and __next__()
methods. The __iter__()
method should return the iterator object itself, while the __next__()
method should return the next value from the iterator or raise StopIteration
if there are no more items.
Example:
class MyRange: def __init__(self, start, end): self.start = start self.end = end def __iter__(self): return self def __next__(self): if self.start >= self.end: raise StopIteration else: self.start += 1 return self.start - 1 my_range = MyRange(0, 5) for value in my_range: print(value)
Output:
0 1 2 3 4
That's it! You now have a basic understanding of Python iterators and how to create and use them. Keep practicing and exploring more advanced features to improve your skills.
How to use iterators in Python:
my_list = [1, 2, 3, 4, 5] my_iterator = iter(my_list) print(next(my_iterator)) # Output: 1 print(next(my_iterator)) # Output: 2
Creating custom iterators in Python:
__iter__
and __next__
methods in a class.class MyIterator: def __init__(self, data): self.data = data self.index = 0 def __iter__(self): return self def __next__(self): if self.index < len(self.data): result = self.data[self.index] self.index += 1 return result else: raise StopIteration my_iterator = MyIterator([1, 2, 3, 4, 5]) for item in my_iterator: print(item)
Iterating over lists and tuples in Python:
my_list = [1, 2, 3, 4, 5] for item in my_list: print(item) my_tuple = (6, 7, 8, 9, 10) for item in my_tuple: print(item)
Using the next() function with iterators:
next()
function is used to fetch the next item from an iterator.my_iterator = iter([1, 2, 3, 4, 5]) print(next(my_iterator)) # Output: 1 print(next(my_iterator)) # Output: 2
Difference between iter() and iteritems() in Python:
iter()
is a built-in function to get an iterator from an iterable, while iteritems()
is not a standard function in Python. If you meant items()
, it is used with dictionaries to get key-value pairs.my_list = [1, 2, 3, 4, 5] my_iterator = iter(my_list) my_dict = {'a': 1, 'b': 2, 'c': 3} for key, value in my_dict.items(): print(key, value)