Iterators in Python

As an object-oriented language, Python treats all data, including variables, functions, lists, tuples, sets, and more, as an object. Some objects are iterable, which means that we can traverse them and they will return their member values one by one.

List, Tuple, and Dictionary are examples of iterable objects.

Iterator & Iterable

Iterators and iterables are crucial concepts in Python programming.

  • Iterables are things you can go through, like lists or collections of data.
  • Iterators are helpers that retrieve items from iterables one by one.

Example: Imagine you have a basket of fruits (that’s an iterable). An iterator is like your hand that picks up one fruit at a time from the basket.

Note: Iterable and iterator are two distinct terms that are occasionally used interchangeably. An iterable is what you can go through, and an iterator is the tool that helps you do it. Remember, the iterable has the items, and the iterator helps you get them one by one!

Creating an Iterator in Python

The Python iterators object is initialized using the iter() method. It uses the next() method for iteration.

.__iter__() Called to initialize the iterator. It must return an iterator object.

.__next__() Called to iterate over the ir=terator. It must return the next value in the data 

stream.

Examples: 

Iterating Through an Iterator

  • x= “ANAS”

ch_iterator = iter(x)

 

print(next(ch_iterator))

print(next(ch_iterator))

print(next(ch_iterator))

print(next(ch_iterator))

 

Output:

A

N

A

S

  • list1 = [“apple”, “banana”, “cherry”]
  • ch_it = iter(list1)

 

  • print(next(ch_it))
  • print(next(ch_it))
  • print(next(ch_it))

Output:

apple

banana

cherry

Here, first, we created an iterator from the list using the iter() method. And then used the next() function to retrieve the elements of the iterator in sequential order.

When we reach the end and there is no more data to be returned, we will get the StopIteration Exception.

Using for Loop

  • my_list = [4, 7, 0]

for element in my_list:

    print(element)

Output:

4

7

0

  • tuple1= (“apple”, “banana”, “cherry”)

 

for x in tuple1:

print(x)

Output:

apple

banana

cherry

The for loop in Python is used to iterate over a sequence of elements, such as a list, tuple, or string.

When we use the for loop with an iterator, the loop will automatically iterate over the elements of the iterator until it is exhausted.

Conclusion:

Iterators are Python objects that allow efficient traversal of iterable objects. As seen in the example of finding multiples of two, they conserve resources by creating values dynamically. Remember to use iter() and next() for iteration, implement __iter__() and __next__() for custom iterators, and understand that Python’s for loop relies on iterators for seamless iteration.

Visited 6 times, 1 visit(s) today