Python iter() Function
iter()It is a built-in function in Python used to convert an iterable object into an iterator.
An iterator is a very important concept in Python,iter()It can create an iterator from any iterable object, allowing the use ofnext()the function to access elements one by one.
Glossary: iter 是 iterator(迭代器)的缩写。
Basic Syntax and Parameters
Syntax Format
iter(object) iter(object, sentinel)
Parameter Description
- Parameter object:
- Type: Iterable object
- Description: The object to be converted to an iterator.
- Parameter sentinel(Optional):
- Type: Arbitrary value
- Description: Sentinel value; iteration stops when this value is reached.
Function Description
- Return value: Returns an iterator object.
- Feature: The iterator can only traverse forward, not backward.
Examples
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))
# Can also iterate 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))
# Can also iterate 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 explanation:
iter()Convert an iterable object into an iterator.- An iterator can only be traversed once; after it is exhausted, it needs to 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 explanation:
- 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 using 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, stop when encountering "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, stop when encountering "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 is used to create custom iteration behavior, typically used with a callable.
Other Extensions
Python3 Built-in Functions