Python __iter__() and __next__() | Converting an object into an iterator

At many instances, we get a need to access an object like an iterator. One way is to form a generator loop but that extends the task and time taken by the programmer. Python eases this task by providing a built-in method  __iter__() for this task.
The __iter__() function returns an iterator for the given object (array, set, tuple, etc. or custom objects). It creates an object that can be accessed one element at a time using __next__() function, which generally comes in handy when dealing with loops.

 Syntax : 

iter(object)
iter(callable, sentinel)
  • Object: The object whose iterator has to be created. It can be a collection object like list or tuple or a user-defined object (using OOPS).
  • Callable, Sentinel: Callable represents a callable object, and sentinel is the value at which the iteration is needed to be terminated, sentinel value represents the end of sequence being iterated.

Exception :  if we call the iterator after all the elements have been iterated, then StopIterationError is raised.

The __iter__() function returns an iterator object that goes through each element of the given object. The next element can be accessed through __next__() function. In the case of callable object and sentinel value, the iteration is done until the value is found or the end of elements reached. In any case, the original object is not modified.

Example 1

listA = ['a','e','i','o','u']

iter_listA = iter(listA)

try:
	print( next(iter_listA))
	print( next(iter_listA))
	print( next(iter_listA))
	print( next(iter_listA))
	print( next(iter_listA))
	print( next(iter_listA)) #StopIteration error
except:
	pass

Output

a

e

i

o

u

Example 2


lst = [11, 22, 33, 44, 55]

iter_lst = iter(lst)
while True:
	try:
		print(iter_lst.__next__())
	except:
		break

Output

11

22

33

44

55

Example 3 

 



listB = ['Cat', 'Bat', 'Sat', 'Mat']


iter_listB = listB.__iter__()

try:
	print(iter_listB.__next__())
	print(iter_listB.__next__())
	print(iter_listB.__next__())
	print(iter_listB.__next__())
	print(iter_listB.__next__()) #StopIteration error
except:
	print(" \nThrowing 'StopIterationError'",
					"I cannot count more.")

Output

Cat
Bat
Sat
Mat
 
Throwing 'StopIterationError' I cannot count more.

Example 4

 

# Python code showing use of iter() using OOPs

class Counter:
	def __init__(self, start, end):
		self.num = start
		self.end = end

	def __iter__(self):
		return self

	def __next__(self):
		if self.num > self.end:
			raise StopIteration
		else:
			self.num += 1
			return self.num - 1
			
			
# Driver code
if __name__ == '__main__' :
	
	a, b = 2, 5
	
	c1 = Counter(a, b)
	c2 = Counter(a, b)
	
	# Way 1-to print the range without iter()
	print ("Print the range without iter()")
	
	for i in c1:
		print ("Eating more Pizzas, counting ", i, end ="\n")
	
	print ("\nPrint the range using iter()\n")
	
	# Way 2- using iter()
	obj = iter(c2)
	try:
		while True: # Print till error raised
			print ("Eating more Pizzas, counting ", next(obj))
	except:
		# when StopIteration raised, Print custom message
		print ("\nDead on overfood, GAME OVER")

Output

Print the range without iter()
Eating more Pizzas, counting  2
Eating more Pizzas, counting  3
Eating more Pizzas, counting  4
Eating more Pizzas, counting  5

Print the range using iter()

Eating more Pizzas, counting  2
Eating more Pizzas, counting  3
Eating more Pizzas, counting  4
Eating more Pizzas, counting  5

Dead on overfood, GAME OVER
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值