Notes

`iter()` Function in Python [ English ]

< Prev Next >

1. Introduction

The iter() function in Python is a built-in function used to convert an iterable object into an iterator. An iterator is an object that allows elements to be accessed one at a time, making it useful for sequential processing of data.

Common iterable objects include lists, tuples, strings, sets, and dictionaries. The iter() function enables us to traverse these objects step by step using the next() function.

2. Syntax

iter(object, sentinel)

Parameters

  1. object An iterable object (such as a list, tuple, or string).

  2. sentinel (optional) A value that signals the end of iteration when using a callable.

3. Return Value


4. Basic Example

numbers = [10, 20, 30]

it = iter(numbers)

print(next(it))
print(next(it))
print(next(it))

Output

10
20
30

Explanation

5. Example with a String

text = "Python"

it = iter(text)

print(next(it))
print(next(it))

Output

P
y

Explanation

6. Using iter() in a Loop

numbers = [1, 2, 3]

it = iter(numbers)

for item in it:
    print(item)

Output

1
2
3

Explanation

7. Handling End of Iteration

numbers = [1, 2]

it = iter(numbers)

while True:
    try:
        print(next(it))
    except StopIteration:
        break

Output

1
2

Explanation

8. Using iter() with Sentinel Value

import random

def get_number():
    return random.randint(1, 5)

for num in iter(get_number, 3):
    print(num)

Explanation

9. Iterable vs Iterator

Term Description
Iterable Object that can be converted into an iterator (list, tuple, string)
Iterator Object that produces elements one at a time using next()

Example:

numbers = [1, 2, 3]
it = iter(numbers)

10. Summary

< Prev Next >