GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — Python iter Function - Complete Guide Python iter FunctionLast modified April 11, 2025
This comprehensive guide explores Python's Basic Definitions
The
Key characteristics: takes an iterable object (or a callable and sentinel),
returns an iterator that implements Basic Iterable Usage
Here's simple usage with different iterable types showing how basic_iter.py
# With lists numbers = [1, 2, 3] num_iter = iter(numbers) print(next(num_iter)) # 1 print(next(num_iter)) # 2 # With strings text = "hello" char_iter = iter(text) print(next(char_iter)) # 'h' print(next(char_iter)) # 'e'
This example shows
The Custom Iterable ObjectsYou can make custom objects iterable by implementing the iterator protocol. This example creates a Countdown class. custom_iter.py
class Countdown:
def __init__(self, start):
self.start = start
def __iter__(self):
return self
def __next__(self):
if self.start <= 0:
raise StopIteration
current = self.start
self.start -= 1
return current
countdown = Countdown(3)
countdown_iter = iter(countdown)
print(next(countdown_iter)) # 3
print(next(countdown_iter)) # 2
print(next(countdown_iter)) # 1
The Countdown class implements both This pattern is common when you need custom iteration behavior beyond what built-in types provide. Using Sentinel Values
The sentinel.py
import random
def random_until_5():
num = random.randint(1, 10)
print(f"Generated: {num}")
return num
five_iter = iter(random_until_5, 5)
for num in five_iter:
print(f"Got: {num}")
This creates an iterator that calls This is useful for creating iterators from functions that produce values until a termination condition is met. File Reading with iter
The sentinel form of file_iter.py
# Read lines until empty line
with open('data.txt') as f:
for line in iter(f.readline, '\n'):
print(line.strip())
# Read fixed-size chunks
with open('large_file.bin', 'rb') as f:
for chunk in iter(lambda: f.read(1024), b''):
process(chunk)
The first example reads lines until an empty line is encountered. The second reads binary data in chunks until EOF.
This demonstrates how Error Handling
The errors.py
try:
print(iter(42))
except TypeError as e:
print(f"Error: {e}") # 'int' object is not iterable
try:
print(iter(lambda: 1, 2, 3)) # Too many arguments
except TypeError as e:
print(f"Error: {e}") # iter() takes at most 2 arguments (3 given)
These examples demonstrate
To make a class work with Best Practices
Source ReferencesAuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. List all Python tutorials. |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |