Python iter() Function
iter() is a built-in Python function that converts an iterable into an iterator.
Iterators are a very important concept in Python;iter() it can create an iterator from any iterable, allowing the next() function to access elements one at a time.
Word meaning: iter 是 iterator(迭代器)的缩写。
Basic syntax and parameters
Syntax format
iter(object) iter(object, sentinel)
Parameter Description
- Parameter object:
- Type: iterable
- Description: the object to convert into an iterator.
- Parameter sentinel(optional):
- Type: any value
- Description: a sentinel value; iteration stops when this value is reached.
Function description
- Return Value: returns an iterator object.
- Feature: an iterator can only be traversed forward, not backward.
Example
Example 1: basic usage
Example
# Create an iterator from a list
my_list = [1, 2, 3]
iterator = iter(my_list)
# Use next() to get elements
print(next(iterator)) # Output: 1
print(next(iterator)) # Output: 2
print(next(iterator)) # Output: 3
# Calling again raises StopIteration
# print(next(iterator))
# It can also be traversed with a for loop
my_list = [1, 2, 3]
for item in iter(my_list):
print(item, end=" ")
# Output: 1 2 3
my_list = [1, 2, 3]
iterator = iter(my_list)
# Use next() to get elements
print(next(iterator)) # Output: 1
print(next(iterator)) # Output: 2
print(next(iterator)) # Output: 3
# Calling again raises StopIteration
# print(next(iterator))
# It can also be traversed with a for loop
my_list = [1, 2, 3]
for item in iter(my_list):
print(item, end=" ")
# Output: 1 2 3
Expected output:
1 2 3 1 2 3
Code analysis:
iter()Convert an iterable into an iterator.- An iterator can only be traversed once; once exhausted it must be recreated.
Example 2: creating from strings and tuples
Example
# String iterator
s = "hello"
iterator = iter(s)
print(next(iterator)) # Output: h
print(next(iterator)) # Output: e
print(next(iterator)) # Output: l
# Tuple iterator
t = (1, 2, 3)
iterator = iter(t)
print(next(iterator)) # Output: 1
print(next(iterator)) # Output: 2
s = "hello"
iterator = iter(s)
print(next(iterator)) # Output: h
print(next(iterator)) # Output: e
print(next(iterator)) # Output: l
# Tuple iterator
t = (1, 2, 3)
iterator = iter(t)
print(next(iterator)) # Output: 1
print(next(iterator)) # Output: 2
Expected output:
h e l 1 2
Code analysis:
- A string iterator returns one character at a time.
- A tuple iterator returns one element at a time.
Example 3: using the sentinel parameter
Example
# Create a custom iterator with sentinel
def fibonacci():
n = 0
while True:
yield n
n += 1
if n > 10:
raise StopIteration
# Use sentinel (stop when a certain value is read)
class ReadUntil:
def __init__(self, data, stop_at):
self.data = data
self.stop_at = stop_at
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index >= len(self.data):
raise StopIteration
value = self.data[self.index]
if value == self.stop_at:
raise StopIteration
self.index += 1
return value
# Create an iterator that stops when it encounters "END"
data = ["a", "b", "c", "END", "d"]
iterator = iter(lambda: ReadUntil(data, "END"), None)
for item in iterator:
print(item, end=" ")
# Output: a b c
def fibonacci():
n = 0
while True:
yield n
n += 1
if n > 10:
raise StopIteration
# Use sentinel (stop when a certain value is read)
class ReadUntil:
def __init__(self, data, stop_at):
self.data = data
self.stop_at = stop_at
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index >= len(self.data):
raise StopIteration
value = self.data[self.index]
if value == self.stop_at:
raise StopIteration
self.index += 1
return value
# Create an iterator that stops when it encounters "END"
data = ["a", "b", "c", "END", "d"]
iterator = iter(lambda: ReadUntil(data, "END"), None)
for item in iterator:
print(item, end=" ")
# Output: a b c
Expected output:
a b c
The sentinel parameter creates custom iteration behavior, usually used together with a callable.
Python3 built-in function