?print-pdf
' Created for
__next__()
: returns the next item of the sequence. On reaching the end, it should raise the StopIteration exception.__iter__()
: returns the iterator object itself.for
loops. Iterators are what Python uses under the hood to loop over these iterables.__iter__()
method, which returns the iterator object (usually, it's just self).__next__()
method, which returns the next item in the sequence. When there are no more items to return, raise the StopIteration exception.
class NumberIterator:
def __init__(self, start, end):
self.current = start # Start value of the iterator
self.end = end # End value for the iterator
def __iter__(self):
# The iterator object is returned here
return self
def __next__(self):
# Check if the current value has reached or exceeded the end value
if self.current >= self.end:
raise StopIteration
self.current += 1
# Return the current value before incrementing
return self.current - 1
# Use the iterator in a loop
for num in NumberIterator(1, 5):
print(num)
iter()
and next()
__iter__()
method that returns the iterator.__next__()
method.
# An iterable object (a list)
my_list = [1, 2, 3]
# Get an iterator using iter()
iterator = iter(my_list)
# Use next() to get the next item from the iterator
print(next(iterator)) # 1
print(next(iterator)) # 2
print(next(iterator)) # 3
# If we call next() again, it will raise StopIteration
# print(next(iterator)) # Uncommenting this will raise StopIteration
class FibonacciIterator:
def __init__(self, n):
self.a, self.b = 0, 1 # Starting values for Fibonacci sequence
self.n = n # Number of Fibonacci numbers to generate
self.count = 0 # Counter to keep track of how many numbers have been generated
def __iter__(self):
return self
def __next__(self):
if self.count >= self.n:
raise StopIteration # Stop when we've generated n numbers
self.a, self.b = self.b, self.a + self.b # Update Fibonacci numbers
self.count += 1 # Inrement count
return self.a
# Example usage: create Fibonacci iterator for first 10 numbers
fibonacci = FibonacciIterator(10)
for number in fibonacci:
print(number, end=",")
def number_generator(start, end):
current = start
while current < end:
yield current
current += 1
# Use the generator in a loop
for num in number_generator(1, 5):
print(num)
yield
instead of return
def foo_generator():
print('generator start')
# yield is almost like return, but it freezes the execution
yield 1
yield 2
print('generator end')
foo_gen = foo_generator()
for x in foo_gen:
print(x)
# generator start
# 1
# 2
# generator end
def simple_generator():
print("Start")
yield 1
print("Resume")
yield 2
print("Resume")
yield 3
print("Done")
gen = simple_generator()
print(next(gen)) # Start -> Yields 1
print(next(gen)) # Resumes -> Yields 2
print(next(gen)) # Resumes -> Yields 3
print(next(gen)) # Raises StopIteration
def number_generator(start, end):
current = start
while current < end:
yield current
current += 1
for num in number_generator(1, 5):
print(num, end=",")
def fibonacci_generator(n):
a = 0
b = 1
for _ in range(n):
yield a
a, b = b, a + b
for number in fibonacci_generator(10):
print(number, end="")
(variable for variable in iterable if condition)
squares = (num**2 for num in range(1,11))
print(squares)
print(list(squares))
# <generator object <genexpr> at 0x7f87ade4dd80>
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
squares = (num**2 for num in range(1,11) if num%2==0)
print(list(squares))
# [4, 16, 36, 64, 100]
error_lines = [] # Create a list to store error lines
with open('./syslog') as file:
for line in file:
if 'error' in line:
error_lines.append(line) # Add matching lines to the list
for line in error_lines:
print(line)
error_lines = (line for line in open('./syslog') if 'error' in line)
for line in error_lines:
print(line)
These slides are based on
customised version of
framework