Python iter()
Function
The iter() function in Python is used to create an iterator from an iterable (like a list, tuple, or string). It plays a key role in enabling for-loops, comprehensions, and lazy evaluation.
Syntax
iter(iterable)
or
iter(callable, sentinel)
Parameters:
iterable
– Any object capable of returning its elements one at a time (like a list, string, tuple, etc.)callable, sentinel
– An alternate form used to create an iterator from a function until a specific value (sentinel) is returned.
Returns:
- An iterator object.
Example: Using iter()
with a List
my_list = [10, 20, 30]
it = iter(my_list)
print(next(it)) # 10
print(next(it)) # 20
print(next(it)) # 30
10
20
30
Example: Looping with iter()
words = ["hello", "world"]
it = iter(words)
for word in it:
print(word)
hello
world
Example: Using iter()
with Callable and Sentinel
# Read input until the user types 'stop'
def get_input():
return input("Enter value: ")
for val in iter(get_input, 'stop'):
print("You entered:", val)
Explanation: This form of iter()
calls the function repeatedly until it returns the sentinel value.
Use Case: Why Use iter()
?
- Used behind the scenes in
for
loops - Manual control over iteration using
next()
- Custom data streaming or lazy evaluation
Common Mistakes
- Trying to use
next()
on an object that is not an iterator - Forgetting that
iter()
does not copy the object; it returns a pointer-like object
Interview Tip
When asked about iterables vs iterators, remember: iter()
converts an iterable into an iterator, which then maintains internal state across next()
calls.
Summary
iter()
is used to create an iterator from an iterable or callable- Works with lists, strings, tuples, dictionaries, and more
- Returns an object compatible with
next()
Practice Problem
Create your own list of numbers and use iter()
with next()
to print each number one-by-one.
nums = [1, 2, 3, 4]
it = iter(nums)
while True:
try:
print(next(it))
except StopIteration:
break