Unit V
Unit V
com
Iterators in Python
Iterators are everywhere in Python. They are elegantly implemented within for
loops, comprehensions, generators etc. but are hidden in plain sight.
Iterator in Python is simply an object that can be iterated upon. An object which
will return data, one element at a time.
Technically speaking, a Python iterator object must implement two special
methods, __iter__() and __next__(), collectively called the iterator protocol.
An object is called iterable if we can get an iterator from it. Most built-in
containers in Python like: list, tuple, string etc. are iterables.
The iter() function (which in turn calls the __iter__() method) returns an iterator
from them.
We use the next() function to manually iterate through all the items of an
iterator. When we reach the end and there is no more data to be returned, it
will raise the StopIteration Exception.
Following is an example.
# define a list
my_list = [4, 7, 0, 3]
# get an iterator using iter()
my_iter = iter(my_list)
# iterate through it using next()
# Output: 4
print(next(my_iter))
# Output: 7
print(next(my_iter))
# next(obj) is same as obj.__next__()
# Output: 0
print(my_iter.__next__())
# Output: 3
print(my_iter.__next__())
# This will raise error, no items left
next(my_iter)
iamriteshkandari 9259069231 [email protected]
Iteration protocol
The iteration protocol in Python is a set of rules that objects must follow in order
to be considered "iterable". The main requirement of the iteration protocol is
that an object must provide a method called __iter__() that returns an iterator
object. The iterator object must have a __next__() method that returns the next
item in the sequence, or raises a StopIteration exception when there are no
more items.
Iterable object
An iterable object is an object that follows the iteration protocol and can be used
in a for loop or with other built-in functions that accept iterable objects, such as
map(), filter(), and sum(). Examples of iterable objects in Python include lists,
tuples, dictionaries, and sets.
For example, let's consider a list:
>>> my_list = [1, 2, 3, 4]
>>> iterable = iter(my_list)
>>> next(iterable)
1
>>> next(iterable)
2
>>> next(iterable)
3
>>> next(iterable)
4
>>> next(iterable)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
As seen above, the list is an iterable object, and when the iter() function is called
on it, an iterator is returned. The next() function is then used to access each item
in the sequence, until a StopIteration exception is raised to indicate that there
are no more items.
iamriteshkandari 9259069231 [email protected]
Use of Generators
Generators in Python are a type of iterable objects that allow you to generate
values one at a time, instead of creating a complete list in memory. This makes
them memory efficient and suitable for handling large data sets. Generators are
defined using the yield keyword in a function, and they can be used with the for
loop or the next function. To create a generator, you define a function like a
normal function but instead of using return, you use yield. When the generator
function is called, it returns a generator object that can be iterated over using a
for loop or the next () function.
Python generators
iamriteshkandari 9259069231 [email protected]
Python generators are special type of iterators that generate values one by one
as they are required, instead of generating all the values and storing them in
memory at once. This allows for efficient usage of memory, as only one value is
stored in memory at a time.
Generators are created using functions with the "yield" keyword instead of the
"return" keyword. The function returns a generator object which can be used to
generate the values.
Here's an example of a generator that generates the first n natural numbers:
def first_n_numbers(n):
i=1
while i <= n:
yield i
i += 1
# Usage
gen = first_n_numbers(5)
for num in gen:
print(num)
# Output:
#1
#2
#3
#4
#5
Assertions
iamriteshkandari 9259069231 [email protected]
An assertion in Python is a statement that tests for a certain condition, and
triggers an error if the condition is not met. An assert statement consists of the
following components:
1. The keyword "assert" - This signals to Python that you are making an
assertion.
2. A condition - This is the expression that is being tested for truth.
3. An optional error message - If the condition is not met, this message will
be displayed as part of the AssertionError.
Here's an example of an assert statement in Python
x=-1
assert x > 0, "x must be positive"
In this example, the condition being tested is x > 0, and the error message is "x
must be positive". If x is less than or equal to zero, an AssertionError will be
raised with the message "x must be positive".