iter() Builtin Function


Python iter()

Python iter() builtin function is used to create an iterator object from a given iterable.

In this tutorial, you will learn the syntax of iter() function, and then its usage with the help of example programs.

Syntax

The syntax of iter() function is

iter(object)
iter(object, sentinel)

where

ParameterDescription
objectAn object.
sentinelA value, which when equals value returned by __next__() method, raises StopIteration. If sentinel is provided, then object must be callable.

Examples

1. Iterator for list object

In the following program, we take a list object in variable x, get its iterator object, and print the items from the iterator object using next() function.

Python Program

x = [5, 7, 0, 4]

x_iter = iter(x)

print(next(x_iter))
print(next(x_iter))
print(next(x_iter))
print(next(x_iter))

Output

5
7
0
4

2. Iterator for string object

Now, we take a string, and get the characters of the string, using iter() function.

Python Program

x = 'hello'

x_iter = iter(x)

print(next(x_iter))
print(next(x_iter))
print(next(x_iter))

Output

h
e
l

Summary

In this tutorial of Python Examples, we learned the syntax of iter() builtin function, and how to get the iterator for an object, with examples.