iter() Builtin Function

Python iter()

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

Syntax

The syntax of iter() function is

iter(object)
iter(object, sentinel)

where

  • object is any valid Python object.
  • sentinel is a 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))
Run

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))
Run

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.