what are Iterators and Iterables in python

You can create an iterator using the built-in iter() function. The iterator is used to loop over the elements of the list. The iterator fetches the value and then automatically points to the next element in the list when it is used with the next() method.

Iterators Vs Iterables

An iterable is an object that can return an iterator. Any object with state that has an iter method and returns an iterator is an iterable.

An Iterator is an object that produces the next value in a sequence when you call next(object) on some object. Moreover, any object with a next method is an iterator.

All iterators are iterable, but all iterables are not iterators. An iterator can only be used in a single for loop, whereas an iterable can be used repeatedly in subsequent for loops.

Iterable classes:

Iterable classes define an iter and a next method.

class Iterable:
    def __iter__(self):
        return self
    def __next__(self):
        #Body of the code

Example:

print a element in the list using iter() and next()

items = [ "I","T","E","R","A","T","H","O","N" ]
rep = iter(items)
a = next(rep) 
print(a)

#Output
#I

print elements one by one

items = [ "I","T","E","R","A","T","H","O","N" ]
iterator = iter(items)
print(next(iterator)) 
print(next(iterator)) 
print(next(iterator)) 
print(next(iterator)) 
print(next(iterator)) 
print(next(iterator)) 
print(next(iterator)) 
print(next(iterator)) 
print(next(iterator)) 

#OUTPUT
#I
#T
#E
#R
#A
#T
#H
#O
#N

Print the elements in the list using an iterator

num = [1,2,3,4,5]
rep = iter(num)
for i in range(len(num)):
    print("Element at index",i,"is:",next(rep))

#Output

#Element at index 0 is: 1
#Element at index 1 is: 2
#Element at index 2 is: 3
#Element at index 3 is: 4
#Element at index 4 is: 5

My Previous Blog

How to send Gmail using python | Just 2 lines: https://iterathon.tech//how-to-send-gmail-using-python-just-2-lines/

How to declare an array in python: https://iterathon.tech//how-to-declare-an-array-in-python/

Difference between Data Science Vs Machine learning? : https://cybrblog.tech/difference-between-data-science-vs-machine-learning/

LEARN SOMETHING NEW ❣️

Similar Posts

Leave a Reply

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