Python iter() Function



The Python iter() function is a built-in function that is used to obtain an iterator from an iterable object. An iterable is an object that enables us to access one item at a time by iterating over them, such as list, tuples, strings, etc.

In the next few sections, we will learn this function in more detail.

Syntax

Following is the syntax of the Python iter() function −

iter(object, sentinel)

Parameters

The Python iter() function accepts two parameters −

  • object − It represents an object such as a list, string, or tuple.

  • sentinel − It is an optional parameter. When the sentinel value is provided, iteration will continue until the value returned by the iterator matches the sentinel.

Return Value

The Python iter() function returns an iterator object.

Examples

In this section, we will see some examples of iter() function −

Example 1

In the code below, we are converting a given list into an iterator object by using the iter() function and then, printing the first two elements with the help of next() function.

numericLst = [55, 44, 33, 22, 11]
iteration = iter(numericLst)
print("The first two items from the iterator is:")
print(next(iteration)) 
print(next(iteration))

Following is an output of the above code −

The first two items from the iterator is:
55
44

Example 2

The code below demonstrates how to use iter() function with the "for loop". Here, we are displaying the elements of the specified list after converting it to iterator object.

numericLst = [55, 44, 33, 22, 11]
iteration = iter(numericLst)
print("All items from the iterator are:")
for item in iteration:
   print(item)

Output of the above code is as follows −

All items from the iterator are:
55
44
33
22
11

Example 3

In the code below a tuple is created and then converted into an iterator object using iter() method. Furthermore, we display the first two elements of this object with the help of "for" and "if" loops.

fruitTuple = ("Grapes", "Orange", "Banana", "Apple")
iterator = iter(fruitTuple)
print("The first two items from the iterator are:")
counter = 0
for item in iterator:
   if counter < 2:
      print(item)
      counter += 1
   else:
      break

Following is the output of the above Python code −

The first two items from the iterator are:
Grapes
Orange

Example 4

The iter() method can also be used with the string to display its characters one at a time as illustrated in the below example.

orgName = "TutorialsPoint"
iterator = iter(orgName)
print("The characters of the given string are:")
for item in iterator:
   print(item)

The above program, on executing, displays the following output −

The characters of the given string are:
T
u
t
o
r
i
a
l
s
P
o
i
n
t
python_built_in_functions.htm
Advertisements