Python iter() method
Last Updated :
11 Dec, 2024
Improve
Python iter()
method is a built-in method that allows to create an iterator from an iterable. An iterator is an object that enables us to traverse through a collection of items one element at a time. Let’s start by understanding how iter()
works with a simple example.
a = [10, 20, 30, 40]
# Convert the list into an iterator
iterator = iter(a)
# Access elements using next()
print(next(iterator))
print(next(iterator))
Output
10 20
Table of Content
Syntax of
iter()
methoditerator = iter(iterable)
Parameters
iterable
: Any object capable of returning its elements one at a time. Examples include lists, tuples, dictionaries, and strings.Return Type
- Returns an iterator object that can be used with the
next()
function or afor
loop to access the elements sequentially.
Examples of iter()
Method
Using iter()
with String
# Convert string to iterator
s = "Python"
iterator = iter(s)
print(next(iterator))
print(next(iterator))
Output
P y
Using iter()
with Dictionary
d = {'a': 1, 'b': 2, 'c': 3}
iterator = iter(d)
for key in iterator:
print(key)
Output
a b c
Using iter()
with Callable and Sentinel
# Generate numbers until sentinel value is encountered
import random
iterator = iter(lambda: random.randint(1, 5), 3)
for num in iterator:
print(num)
Output
5 5
Frequently Asked Questions on iter()
Method
Q1: What happens if we call next()
on an iterator with no elements left?
Python raises a
StopIteration
exception, indicating the end of the iterator.
Q2: Can we iterate over an iterator more than once?
No, iterators are exhausted after one full iteration. We must recreate the iterator to iterate again.
Q3: How is iter()
different from a loop?
A loop implicitly handles the iteration process while
iter()
gives us manual control over iteration, element by element.
Q4: Can custom classes use iter()
?
Yes, custom classes implementing the
__iter__()
and__next__()
methods can work withiter()
.