Python iter() Function

Returns an iterator object, which can be used to iterate over the collection. Because collections have built-in iterators, the iter() function applied to collections is not necessary, as the example demonstrates.

Syntax

Python
iter(object, sentinel = None)

Parameters

ParameterDescription
object Required. The object to convert into an iterable
sentinel Optional. The value that indicates the end of a sequence.

Example

Python
print('Using iter:')
myList = ['apples', 'oranges', 'bananas']
i = iter(myList)
for item in i:
    print(f'\t{item}')

print("Using the collection's built-in iterator:")
for item in myList:
    print(f'\t{item}')

Output

Using iter:
    apples
    oranges
    bananas
Using the collection's built-in iterator:
    apples
    oranges
    bananas

Where the iter() function comes in handy is when it is used with the option second parameter, the sentinel. In this case, the first parameter is a function that iter() calls until the return value equals the sentinel value.

This example is slightly contrived as it would be better to use the range() function, but it illustrates how the iter() function can be used to call the same function over and over until the return value equals the sentinel value.

Example

Python
class Counter():
    n = 0

def count(self):
    self.n += 1
    return self.n - 1

counter = Counter()
for item in iter(counter.count, 5):
    print(item)

Output

0
1
2
3
4

Notes

Note that we must use a class to initialize any variables that the iterable function requires. This code results in an exception because an iterator function (also called a generator) can only reference local variables.

Example:
Python
n = 0
def count():
    n += 1
    return n - 1

for item in iter(count, 5):
    print(item)
Output:
Traceback (most recent call last):
  File "itertest.py", line 6, in <module>
    for item in iter(count, 5):
  File "C:\projects\PythonLanguageRef\PythonTests\BuiltInFunctions.py", line 3, in count
    n += 1
UnboundLocalError: local variable 'n' referenced before assignment