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_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__().