iterator using iter()


Youtube Live session on Tkinter

We get an iterator ( output ) from an iterable object ( input ) by using iter function.
iter(iterable_obj,sentinel)
iterable_obj: Required, Object which can be iterated
sentinel: Optional, Value specifying the end of sequence

Example of iterable objects are : List, tuple, dictionary , string
my_str='plus2net'      # a string variable is declared 
my_str=iter(my_str)    # returns an iterator

print(next(my_str))    # p
print(next(my_str))    # l
print(next(my_str))    # u
next() returns the the next item from the iterator Example using one List
my_list=[4,3,5,1]       # declaring a List
my_list1=iter(my_list)  # returns iterator 

print(next(my_list1))   # 4
print(next(my_list1))   # 3
print(next(my_list1))   # 5
print(next(my_list1))   # 1

Type of Iterator

We can check the type of variable we get before and after using iter() function
my_str='plus2net'     # a string variable is declared
print(type(my_str))   # <class 'str'>  
my_str=iter(my_str)   # returns iterator
print(type(my_str))   # <class 'str_iterator'> 

my_list=[4,3,5,1,2]   # declaring a List
print(type(my_list))  # <class 'list'> 
my_list=iter(my_list) # returns iterator
print(type(my_list))  # <class 'list_iterator'>   

Exception handling with iter()

What happens if we try to use iter() with a not iterable object as input? We will get TypeError
my_str=4356   # integer variable which is not iterable
my_str=iter(my_str)
Output is here
     my_str=iter(my_str)
TypeError: 'int' object is not iterable
We can use Try Except to handle such error
my_str=4356  # integer variable which is not iterable
try:
    my_str=iter(my_str)
except TypeError as my_msg:
    print ("This is a TypeError")
    print (my_msg)
except:
    print ("Some other error has occured")
Output is here
This is a TypeError
'int' object is not iterable
What happens when there is no item left to return with next() ? We will get StopIteration error
my_str='abc'  
my_str=iter(my_str)
try:
    print(next(my_str))   # a
    print(next(my_str))   # b
    print(next(my_str))   # c
    print(next(my_str))   # Error
except StopIteration:
    print ("This is a StopIteration error")
    
except:
    print ("Some other error has occured")
Output is here
a
b
c
This is a StopIteration error
We can use default value with next() to return when no value is left. In this case there will be no error as default vlaue is returned. In this example we have kept 'x' as default value to return if no value is left. After printing 'c' there is no value to return so 'x' is returned always.
my_str='abc'  
my_str=iter(my_str)
print(next(my_str))       # a
print(next(my_str))       # b
print(next(my_str, 'x'))  # c
print(next(my_str, 'x'))  # x
print(next(my_str, 'x'))  # x
We can create Iterable object having methods __iter__() and __next__().
class my_iter():

    def __iter__(self):
        self.x=1
        return self

    def __next__(self):
        x=self.x
        self.x=self.x+1
        return x

my_obj=my_iter()
my_iter=iter(my_obj)

print(next(my_iter))  # 1
print(next(my_iter))  # 2
print(next(my_iter))  # 3
We can create StopIteration exception by using raise
class my_iter():

    def __iter__(self):
        self.x=1
        return self

    def __next__(self):
        x=self.x
        self.x=self.x+1
        if(x<5):
         return x
        else:
         raise StopIteration    

my_obj=my_iter()
my_iter=iter(my_obj)

print(next(my_iter))  # 1
print(next(my_iter))  # 2
print(next(my_iter))  # 3
print(next(my_iter))  # 4
print(next(my_iter))  # Error : StopIteration
All Built in Functions in Python any() Generator - Tutorials
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer