Python Iterators - iter() and next()

Learn the usage of Python iterators by visualizing how a for loop works in Python with examples.

Python Iterators - iter() and next()

Topics Covered

  1. Difference between sequence and an iterable
  2. What are iterators?
  3. next() in Python
  4. for loop - Behind the scenes
  5. Is a file object an iterator?


Difference between sequence and an iterable

A sequence is an ordered collection of values. Once a list is initialized, the index of the values will not change. Some examples of sequences are lists, dictionaries, tuples and strings.

Iterables are a collection of values over which you can loop over. All sequences are iterables, but not all iterables are sequences. For example, Sets.

x = {12, 6, 9}
print(x)

# Result
>> {6, 9, 12}

So the order in which the values in the set are initialized is not the way it appears. Also, Sets return only unique elements. Learn more about Python Sets here.


What are iterators?

Iterators are objects that manage iteration over an iterable. An iterator has an iteration set - it knows the current element and also the next element in the iterable.

To create an iterator from an iterable, you can pass it through
the iter() method.

Code

my_list = [1, 2, 3]
my_list_iter = iter(my_list)

print(type(my_list))
print(type(my_list_iter))

Output

<class 'list'>
<class 'list_iterator'>

next() in Python

An iterator uses next() method for iteration. It returns a StopIteration Exception when it runs out of elements.

Code

my_list = [1, 2, 3]
my_list_iter = iter(my_list)

print(next(my_list_iter))
print(next(my_list_iter))
print(next(my_list_iter))
print(next(my_list_iter))

Output

1
2
3
Traceback (most recent call last):
  File "some_file_location", line 7, in <module>
    print(next(my_list_iter))
StopIteration

for loop - Behind the scene

When you use a for loop to iterate through an iterable, it internally converts the iterable to an iterator and then uses the next() method to return the next element.

You can visualize the internal working of a for loop, similar to the code below.

Code

my_list = [1, 2, 3]
my_list_iter = iter(my_list)

while True:
    try:
        print(next(my_list_iter))
    except StopIteration:
        break

Output

1
2
3

To understand the above code, you need to know that try and except statements run different actions and catch exceptions that might occur during its execution. You can learn more about it here.

Python Exception Handling: Try, Except, Else and Finally
An example based guide to handle Python exceptions using try, except, else and finally keywords.

A similar operation happens for other data types too.

Code

# Strings
name = "Pylenin"
for char in name:
    print(char, end=" ")
print() # Empty print for better readability

# Tuples
my_tuple = (1, 2, 3)
for elem in my_tuple:
    print(elem, end=" ")
print() # Empty print for better readability

# Dictionary
my_dict = {"name":"Pylenin",
           "age": 28}
for key, value in my_dict.items():
    print(key, value)

# Even sets
some_set = {1, 2, 3, 4, 3, 4}
for elem in some_set:
    print(elem, end = " ")

Output

P y l e n i n 
1 2 3 
name Pylenin
age 28
1 2 3 4 

Is a file object an iterator?

Yes! When you are working with file objects, you don’t have to pass them through the iter() function. A file object is its own iterator.

The example below tries to read a CSV file and use the next() method directly on the file handler object.

Code

f = open(file="world_cyclones.csv")

print(next(f))
print(next(f))

Output

Storm name,Dates active,Max windkm/h (mph),Pressure(hPa),Areas affected,Damage(USD),Deaths,Refs

Damien,February 2 2011,165 (105),955,"Northern Australia, Kimberley",$4.3 million,None,

Problems

  1. Write a Python program to convert range(7) into an iterator and use the next() method to print all its content.

  2. What will the following code return?

    my_info = ["Lenin", "Mishra", 28, "Amsterdam"]
    
    _, value = my_info
    
    print(value)
    

Subscribe to Pylenin

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe