Python iter() Function

Python iter() function “returns an iterator for the given argument.”

Syntax

iter(object, sentinel)

Parameters

  1. Object: It is an object whose iterator must be created (settuple, list, dictionary, etc.).
  2. sentinel (Optional) – It is the special value used to represent the end of a sequence.

Return value

The iter() method returns:

  1. It is an iterator object for the given argument until the sentinel character is found
  2. TypeError for a user-defined object that doesn’t implement __iter__(), and __next__() or __getitem()__

Example 1: How to Use Python iter() Method

data = iter(['millie', 'finn', 'gaten', 'caleb'])

print(next(data))
print(next(data))
print(next(data))
print(next(data))

We passed a list to the iter() function in the above code and printed the item using the next() function.

Example 2: Using the custom project

Define the custom object and then iterate that object using the next() function.

class Display:
 def __init__(self, count):
 self.count = count

 def __iter__(self):
   self.data = 0
   return self

 def __next__(self):
   if(self.data >= self.count):
     raise StopIteration
      self.data += 1
   return self.data

num = Display(2)

printData = iter(num)

# prints '1'
print(next(printData))

# prints '2'
print(next(printData))

# raises StopIteration
print(next(printData))

Output

1
2
Traceback (most recent call last):
 File "app.py", line 26, in <module>
 print(next(printData))
 File "app.py", line 11, in __next__
 raise StopIteration
StopIteration

Example 3: Python iter() with Sentinel Parameter

class HelloBro:

  def __init__(self):
    self.start = 1

  def __iter__(self):
    return self

  def __next__(self):
    self.start *= 2
    return self.start

 __call__ = __next__


main_iter = iter(HelloBro(), 16)

for x in main_iter:
  print(x)

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.