Python iter() Function: Learn to Create Iterators with Examples

Overview

When working with Python, there are times when you need to retrieve elements from a collection one at a time instead of processing the entire collection at once. This approach is more memory efficient and forms the foundation of Python’s iteration system.

The iter() function plays a key role in this process. In this tutorial, you’ll learn what the iter() function does, how it creates iterators, its syntax, parameters, return value, the special sentinel form of iter(), and practical examples of using it in Python programs.

💡 Tip: Before learning this concept in detail, explore our Python Iteration Tutorial to understand how iteration works in Python.

Introduction: What Is the Python iter() Function?

The iter() function is a built-in Python function that creates an iterator from an iterable object. An iterable is any object whose elements can be processed one at a time, such as a list, tuple, string, dictionary, set, or range().

Once an iterator has been created, it returns one element at a time during iteration. Although you can create an iterator manually by calling iter(), Python automatically does this whenever a for loop iterates over an iterable.

Let’s see how the iter() function works with a simple example

Before exploring practical examples, let’s first understand the syntax, parameters, return value, and how the iter() function works.

Syntax, Parameters, Return Value & Examples: Python iter() Function

Syntax

The iter() function supports two forms of syntax. The first creates an iterator from an iterable object, while the second repeatedly calls a function until a specified value is returned.

Syntax 1: Creating an Iterator from an Iterable

iter(iterable)

This is the most commonly used form of the iter() function. It accepts an iterable object and returns an iterator that retrieves one element at a time.

Syntax 2: Sentinel Form

iter(callable, sentinel)

This form repeatedly calls a callable object until it returns the specified sentinel value. Although it is less common than the first form, it is useful when processing data until a particular value or condition is reached.

Parameters

The parameters accepted by the iter() function depend on which form of the syntax you use.

Parameter Description
iterable An iterable object such as a list, tuple, string, dictionary, set, or range(). The iter() function creates an iterator from this object.
callable A callable object or function that is invoked repeatedly when using the sentinel form.
sentinel A value that stops the iteration when it is returned by the callable.

Return Value

The iter() function returns an iterator object. The exact type of the iterator depends on the iterable passed to the function.

Return Value Description
Iterator Object Returns an iterator that retrieves one element at a time from the specified iterable.
Note: The returned iterator works together with the next() function to retrieve elements one by one until all elements have been processed.

Quick Example

The following example shows how the iter() function creates an iterator from a list and how the next() function retrieves its elements one by one.

fruits = ["Apple", "Banana", "Mango"]

iterator = iter(fruits)

print(next(iterator))
print(next(iterator))
print(next(iterator))


# Output
Apple
Banana
Mango

In this example, iter() creates an iterator from the list, and each call to next() retrieves the next element in sequence until all the elements have been returned.

How the Python iter() Function Works

The iter() function converts an iterable object into an iterator. Once the iterator has been created, Python retrieves its elements one at a time by calling the next() function until no elements remain.

The process can be understood in four simple steps:

  1. An iterable object, such as a list, tuple, string, dictionary, set, or range(), is passed to the iter() function.
  2. The iter() function creates and returns an iterator object.
  3. Each call to the next() function retrieves the next available element from the iterator.
  4. After all elements have been returned, the iterator raises a StopIteration exception to indicate that the iteration has finished.

Iteration Flow

Iterable
      │
      ▼
iter()
      │
      ▼
Iterator
      │
      ▼
next()
      │
      ▼
Next Element
      │
      ▼
Repeat until all elements are returned
      │
      ▼
StopIteration
Note: When using a for loop, Python automatically creates the iterator by calling iter() and repeatedly retrieves elements using next(). The StopIteration exception is also handled automatically, so it is usually seen only when calling next() manually.

Python iter() Function Examples

The following examples demonstrate different ways to use the iter() function. Each example introduces a new concept, helping you understand how the function works with different types of iterable objects and in real-world situations.

Example 1: Create an Iterator from a List

A list is one of the most common iterable objects in Python. The iter() function converts the list into an iterator, allowing its elements to be retrieved one at a time.

fruits = ["Apple", "Banana", "Mango"]

iterator = iter(fruits)

print(next(iterator))
print(next(iterator))
print(next(iterator))


# Output
Apple
Banana
Mango

Explanation: In this example, iter() creates an iterator from the list, and each call to next() returns the next available element until the list has been completely processed.

Example 2: Create an Iterator from a Tuple

The iter() function works with tuples in the same way as it does with lists.

colors = ("Red", "Green", "Blue")

iterator = iter(colors)

print(next(iterator))
print(next(iterator))
print(next(iterator))


# Output
Red
Green
Blue

Explanation: Although tuples cannot be modified, they are iterable. The iterator simply moves through each tuple element in sequence.

Example 3: Create an Iterator from a String

Strings are also iterable. Instead of returning words, the iterator retrieves one character at a time.

language = "Python"

iterator = iter(language)

print(next(iterator))
print(next(iterator))
print(next(iterator))


# Output
P
y
t

Explanation: Each character in the string is treated as an individual element, allowing the iterator to process the text one character at a time.

Example 4: Using iter() with next()

One advantage of creating an iterator manually is that you decide exactly when the next element should be retrieved.

numbers = [10, 20, 30]

iterator = iter(numbers)

print(next(iterator))

print("Processing...")

print(next(iterator))


# Output
10
Processing...
20

Explanation: Unlike a for loop, which retrieves elements automatically, calling next() lets you pause and continue the iteration whenever needed.

Example 5: Using iter() with range()

The iter() function can also create an iterator from a range() object.

numbers = iter(range(1, 6))

print(next(numbers))
print(next(numbers))
print(next(numbers))


# Output
1
2
3

Explanation: The iterator retrieves each number only when it is requested. This makes range() suitable for working with large sequences efficiently.

Example 6: Using the Sentinel Form

The second form of iter() repeatedly calls a function until it returns a specified sentinel value.

numbers = iter(lambda: int(input("Enter a number: ")), 0)

for number in numbers:
    print("You entered:", number)


# Sample Input
5
8
3
0


# Output
You entered: 5
You entered: 8
You entered: 3

Explanation: The lambda function is called repeatedly. As soon as the user enters 0, which is the sentinel value, the iteration stops automatically.

Example 7: [Advanced] Reading Values Until a Sentinel Value

The sentinel form of the iter() function can repeatedly call a function until it returns a predefined stopping value. This technique is useful when the number of values to process is not known in advance.

values = ["A", "B", "C", "END"]

index = -1

def get_value():
    global index
    index += 1
    return values[index]

iterator = iter(get_value, "END")

for value in iterator:
    print(value)


# Output
A
B
C

Explanation: In this example, get_value() is called repeatedly by iter(). Each call returns the next value from the list. When the function returns "END", which is the sentinel value, the iteration stops automatically without processing that value.

Note: This is an advanced example intended to demonstrate the sentinel form of the iter() function. If concepts such as functions or the global keyword are unfamiliar, don’t worry—they will be covered in later tutorials.

Common Use Cases of the Python iter() Function

Although Python automatically uses the iter() function in many situations, there are times when creating an iterator manually gives you greater control over the iteration process. Some common use cases include:

  • Creating an iterator from an iterable such as a list, tuple, string, dictionary, set, or range().
  • Retrieving elements one at a time by combining iter() with the next() function.
  • Processing large datasets efficiently without loading or handling every element at once.
  • Using the sentinel form to repeatedly call a function until a specified stopping value is returned.

Common Beginner Mistakes: Python iter() Function

When learning the iter() function, beginners often misunderstand how iterators work because Python usually creates them automatically inside for loops. Being aware of these common mistakes can help you avoid confusion.

  1. Confusing an iterable with an iterator: An iterable stores or provides data, while an iterator retrieves one element at a time.
  2. Creating an iterator but never using next(): Calling iter() only creates the iterator. Elements are retrieved only when next() is called or the iterator is used in a for loop.
  3. Calling next() after the iterator is exhausted: Once all elements have been returned, another call to next() raises a StopIteration exception.
  4. Expecting an iterator to restart automatically: After an iterator reaches the end, create a new iterator by calling iter() again if you want to iterate over the data from the beginning.

Key Takeaways: Python iter() Function

Here are the key concepts to remember about Python’s iter() function:

  • The iter() function creates an iterator from an iterable object.
  • An iterator retrieves one element at a time and works together with the next() function.
  • The iter() function supports two forms: iter(iterable) and iter(callable, sentinel).
  • Python automatically calls the iter() function when a for loop begins iterating over an iterable.
  • Understanding the iter() function makes it easier to learn iterators, generators, file handling, and Python’s iteration system.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top