WHAT IS PYTHON ITERATOR?

481 viewsPYTHONPython
0

WHAT IS PYTHON ITERATOR?

Saraswat World Changed status to publish June 16, 2023
0
PYTHON ITERATORS

An Iterator is an object that contains a countable no. of values or elements that can be traversed.

An iterator allows a programmer to traverse through all the elements of a collection or iterable objects.

An iterator is an object which implements the iterator protocol, which consist of the methods __iter__() andย __next__().

WHAT IS THE DIFFERENCE BETWEEN ITERATOR AND ITERABLE?

Collection of elements like Lists, Tuples, Dictionaries, Strings, and Sets are all iterable objects. All these objects have an iter() method which is used to get an iterator.

Example is provided below to show that the iterator is returned, from iterable object i.e. a Tuple named fruits, by using iter() method. Iterator allows traversing on values by next() method to print each value.

Python Code

fruits = ("apple", "banana", "cherry") #Tuple-Iterable Object
myiterator = iter(fruits)  #Iterator generated

print(next(myiterator))   
print(next(myiterator))
print(next(myiterator))

Output

apple
banana
cherry
Saraswat World Changed status to publish June 16, 2023
Write your answer.

Posted

in

Tags:

Comments

Leave a Reply

A Tribute to Dilip Kumar