iter() function in Python

The iter() function in Python returns an iterator from an iterable object.

Built-in Functions Updated 18 Mar 2024 3 min read

Overview

An iterator in Python is an object through which the elements of a container can be accessed one after another(Unless some iterators skip some elements through custom implementation). Every time a for loop in Python is used to iterate over a container like list, the for loop obtains an iterator object from the __iter__() method of the container. The for loop makes calls to the __next__() method on the iterator, until it is terminated by a StopIteration exception. These steps are performed by the for loop internally as the for loop is executed.

The built-in function iter() returns an iterator object from a container which follows the iterator protocol. As an itertaor is used internally by the for loop, the iterator obtained through the iter(), can be explicitly used for accessing the elements through various usage patterns.

Example 1

In the Python example below, CSV data is iterated without using a for loop. Iterator is explicitly obtained through iter() function and the __next__() function is called for iteration, till the StopIteration is raised as the iterator moves past the iterable elements.

python
# Example Python program that obtains an iterator

            # object from an iterable using the built_in function

            # __iter__()

            csvRows         = [["place_id", "place_name", "place_temp", "place_temp"],

                              [1, "New York", 40.05, 1006],

                              [],

                              [2, "London", 50.29, 1017],

                              [3, "Paris", 47.05, 1017],

                              [4, "Dubai", 89.94, 1013],

                              [5, "Bengaluru", 88.57, 1016],

                              [6, "Singapore", 81.72, 1012 ],

                              [7, "Tokyo", 42.12, 1001 ],

                              ]

# Get an iterator

            vowels_iter = iter(csvRows)

            print(type(vowels_iter))

# Move past the header of the comma separated values

            header = vowels_iter.__next__()

try:

                while True:

                    fields = vowels_iter.__next__()

                    # Print after simple length check

                    if len(fields) == 4:

                        print(fields)

                    else:

                        print("Skipping an invalid record")

            except StopIteration:

                print("Done printing")

Output

Output
<class 'list_iterator'>

[1, 'New York', 40.05, 1006]

Skipping an invalid record

[2, 'London', 50.29, 1017]

[3, 'Paris', 47.05, 1017]

[4, 'Dubai', 89.94, 1013]

[5, 'Bengaluru', 88.57, 1016]

[6, 'Singapore', 81.72, 1012]

[7, 'Tokyo', 42.12, 1001]

Done printing

Example 2

The quotes are iterated by two iterators independently to compute different analytics using the same data.

python
# Example Python program that creates multiple iterators

            # from the same container(i.e, iterable) and passes them to

            # different functions. These functions may iterate over the iterators

            # independently and process/consume the elements differently.

dailyQuote = [["id", "scrip", "price", "qty", "yearly_high", "yearly_low"],

                             [1, "MSFT", 425.54, 21.87, 427.82, 269.52],

                             [2, "GOOG", 149.57, 25.22, 155.20, 100.28],

                             [3, "META", 507.84, 17.20, 523.57, 197.90],

                             [4, "AAPL", 178.36, 62.98, 199.62, 155.98]]

# Do some price analytics across scrips

            def analysePrice(aIter):

                priceTotal = 0

    try:

                    header = aIter.__next__()

                    while True:

                        oneQuote     = aIter.__next__()

                        priceIter     = iter(oneQuote)

            scrip_id      = priceIter.__next__()

                        scrip_name  = priceIter.__next__()

                        priceTotal     = priceTotal + priceIter.__next__()

                except StopIteration:

                    print("Price iterator exhausted")

    print("Total Price:%.2f"%priceTotal)

# Do some volume analytics across scrips

            def analyseVolume(aIter):

                volumeTotal = 0

                scripCount  = 0

    # Skip the first record

                quote = aIter.__next__()

    try:

                    while True:

                        quote = aIter.__next__()

                        volumeIter = iter(quote)

            id = volumeIter.__next__()

                        scrip = volumeIter.__next__()

                        price = volumeIter.__next__()

                        volumeTotal = volumeTotal + volumeIter.__next__()

                        scripCount = scripCount + 1

                        meanVolume = volumeTotal/scripCount

                except:

                    print("Volume iterator exhausted")

                print("Mean volume in millions:%.2f"%meanVolume)

# Obtain two iterators and pass on to different analytics

            priceIter     = iter(dailyQuote)

            volumeIter     = iter(dailyQuote)

# Perform analysis of quotes

            analysePrice(priceIter)

            analyseVolume(volumeIter)

Output

Output
Price iterator exhausted

Total Price:1261.31

Volume iterator exhausted

Mean volume in millions:31.82

Example 3

This Python example uses two iterables - one a list and another a set. The example iterates over both the iterables and prints the tuples using the zip() built-in function.

python
# Example Python program that itrates over

            # two iterators and produces tuples using zip()

            # the function

# A Python list

            iterable1 = ["w", "x", "y" ,"z"]

# A Python set - prime numbers between ten and twenty

            iterable2 = {11, 33 , 17, 19}

# Obtain the iterator for the list

            i1 = iter(iterable1)

# Obtain the iterator for the set

            i2 = iter(iterable2)

# Iterate over a list and set

            iterList = [i1, i2]

zipped = zip(*iterList)

for i in zipped:

                print(i)

Output

Output
('w', 11)

('x', 33)

('y', 19)

('z', 17)