The iter() is an inbuilt function in Python that returns the iterator object.

Python iter function:

Signature

The signature for the iter() function is as shown below.

l=iter(object,sentinel)

Parameters and return type

  • This method takes an object to convert. The sentinel represents the end of the sequence. The sentinel parameter is given if and only if the object is callable. But, if an object is a collection type like list, tuple, etc., we cannot use this parameter.
  • However, it returns an iterator object.

Python Built-in Function iter Examples:

Example 1: For example, let us initialize a list with city names. Thereafter, we will convert this list to an iterator. Then, we can use the next method to retrieve the iterator till the end of the list. The code given below prints all the elements of a list.

#Initializing
city = ["Delhi","Mumbai", "Hyderabad"]
# converting list to iterator
city = iter(city)
# Using iter()
while (1):
    e = next(city, 'End of list')
    if e == 'End of list':
        print('List ended')
        break
    else:
        print(e)

Output

Delhi
Mumbai
Hyderabad
List ended

Example 2: In this example, we will take a string and a dictionary. In the next step, we have to convert this string and dictionary to an iterator object. Thereafter, we will call next to print the value of the string and dictionary.

#Initializing
s = "python"
d={"1":"One","2":"Two","3":"Three"}
#Converting to iterator
s=iter(s)
d=iter(d)
#Using iter and printing
print("Next string character- ",(next(s)))
print("Next dictionary element - ",(next(d)))

Output

Next string character - p
Next dictionary - 1

Example 3: For this example, we will define a class Num and overwrite its next method. Also, we will pass a number as a parameter, that will increment by 5 till it reaches the maximum value given as 30.

#defining class
class Num:
    def __init__(self, n, max):
        self.n = n
        self.max = max
 
    def __iter__(self):
        return self
 
    def __next__(self):
        self.n = self.n + 5
        if self.n >= self.max:
            raise StopIteration
        else:
            return self.n
 
x = Num(5, 30)
iterator = iter(x)
for item in iterator:
    print(item)

Output

10
15
20
25

Conclusion

The iter() function returns an iterator object.

Happy Learning 🙂

Leave A Comment