Python iter()

varunPatel7537433413's avatar
Published May 19, 2023Updated Oct 1, 2024

The iter() function is a built-in function in Python that returns an iterator from an iterable object, such as a list, tuple, string, or any object that implements the iterator protocol.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

iter(object, sentinel)
  • object: A required argument that represents an iterable object such as a list, tuple, string, or any object that follows iterator or sequence protocol.
  • sentinel: An optional argument that represents the end of the sequence.

Note: sentinel parameter is used to repeatedly call a function until a specific value is returned, which stops the iteration.

Example 1

This example demonstrates the use of the iter() function to create an iterator from a list and retrieve its elements one by one using the next() function:

# Example of iter() function without sentinel
fruits = ['apples', 'bananas', 'oranges']
# Creating an iterator from the list
my_iterator = iter(fruits)
print('Fruits:')
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))

The output would be:

Fruits:
apples
bananas
oranges

Example 2

This example demonstrates the use of the iter() function with a callable and a sentinel value, repeatedly calling the function until the sentinel is returned:

from functools import partial
import random
# iter() method with a callable and a sentinel argument os 7
def get_random_num(a, b):
return random.randint(a, b)
another_iterator = iter(partial(get_random_num, 1, 10), 7)
print('\nNumbers: ')
# Loop will run till 7 is returned
for i in another_iterator:
print(i)

The output would be:

Numbers:
2
8
1
6
9
5
8
2
9
5
2
9
4

Note: The output varies with each execution due to random integer generation, continuing until the sentinel value is encountered.

Codebyte Example

Code
Output

All contributors

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours