Author - StudySection Post Views - 95 views
Iterator pattern

Explain the Iterator pattern with an example in Python

Introduction:

Everything in Python is considered an object, including variables, functions, lists, tuples, sets, etc. In python, some objects are iterable, which means we can iterate over them and they will return their member value one by one.

Some iterable objects are Lists, Tuples, and dictionaries.
Iterators in python are also objects, just like other things. It is used for iterating over iterable objects. This means we can use iterators on lists, tuples, dictionaries, and strings.
They are implemented using two unique methods: iter () and next(). They are together called iterator protocol.
Let’s learn how to use iterators

Using Python Iterators

iter(): This method is used to create the iterator over the iterable object. It returns the object of an iterator.
next(): This method returns the next value from the object.
We can use both methods to iterate over a variable.

Example:

mylist = ['This', 'is', 'Python' ,'List'] myIter = iter(mylist)
print(myIter)
// output: <list_iterator object at 0x7fd062b7f250>
print(next(myIter))
// output: This
print(next(myIter))
// output: is
print(next(myIter))
// output: python
print(next(myIter))
// output: list

In this example, we can see that printing myIter returns an iterator object.
Once we have the iterator object we use next() to traverse through its values. Using this, we get all the values included in the python iterator.
If we try to run next() again then we will get a StopIteration exception:
Traceback (most recent call last):
File “/home/webner/iter.py”, line 9, in <module>
print(next(myIter))
StopIteration

People having good command over the French language can get a French certification from StudySection. StudySection offers both beginner level and expert level French Certification Exams to test the ability to communicate in the French language.

Leave a Reply

Your email address will not be published. Required fields are marked *

fiteesports.com rivierarw.com cratosroyalbet betwoon grandpashabet grandpashabet giriş deneme bonusu veren siteler casino siteleri