Python Logo

Iterator


What are Python iterators?

Python iterators are objects that can be iterated over to produce a sequence of values. Iterators are created using the iter() function. The iter() function takes an iterable object as an argument and returns an iterator object.

Iterable objects are objects that can be iterated over to produce a sequence of values. Examples of iterable objects include lists, tuples, strings, and dictionaries.

Example:

 

Python

# Create a list of numbers
my_list = [1, 2, 3, 4, 5]

# Create an iterator object from the list
my_iterator = iter(my_list)

# Print the next value in the iterator
print(next(my_iterator))

# Print the next value in the iterator
print(next(my_iterator))

# ...

# Print the last value in the iterator
print(next(my_iterator))
 

Output:

 

1
2
3
4
5
 

Using iterators in for loops

Iterators can be used in for loops to iterate over a sequence of values. The for loop will execute the loop body for each value in the iterator.

Example:

 

Python

# Create a list of numbers
my_list = [1, 2, 3, 4, 5]

# Iterate over the list using a for loop
for number in my_list:
  print(number)
 

Output:

 

1
2
3
4
5
 

Stopping an iterator

To stop an iterator, you can use the StopIteration exception. The StopIteration exception is raised when the iterator reaches the end of the sequence of values.

Example:

 

Python

# Create an iterator object from a list
my_iterator = iter([1, 2, 3, 4, 5])

# Iterate over the iterator until the StopIteration exception is raised
while True:
  try:
    print(next(my_iterator))
  except StopIteration:
    break
 

Output:

 

1
2
3
4
5
 

Creating custom iterators

You can create custom iterators by implementing the __iter__() and __next__() methods. The __iter__() method returns the iterator object itself. The __next__() method returns the next value in the sequence of values, or raises the StopIteration exception if there are no more values.

Example:

 

Python

class MyIterator:
  def

 __init__(self, sequence):
    self.sequence = sequence
    self.index = 0



  def

 __iter__(self):


    return self

  def

 __next__(self):


    if self.index >= len(self.sequence):
      raise StopIteration

    value = self.sequence[self.index]
    self.index += 1

    return value

# Create a list of numbers
my_list = [1, 2, 3, 4, 5]

# Create a custom iterator from the list
my_iterator = MyIterator(my_list)

# Iterate over the iterator using a for loop
for number in my_iterator:
  print(number)
 

Output:

 

1
2
3
4
5
 

Conclusion

Python iterators are a powerful tool that can be used to iterate over a sequence of values. By understanding how to use Python iterators, you can write more efficient and readable code.