InterviewSolution
| 1. |
Python's standard library has a built-in function next(). For what purpose is it used? |
|
Answer» The built-in next() function calls __next__() method of iterator object to retrieve next item in it. So the next question WOULD be – what is an iterator? An object representing stream of data is an iterator. One element from the stream is retrieved at a time. It follows iterator protocol which requires it to support __iter__() and __next__() methods. Python’s built-in method iter() implements __iter__() method and next() implements __next__() method. It receives an iterable and returns iterator object. Python uses iterators implicitly while working with collection data types such as list, tuple or string. That's why these data types are called iterables. We normally USE ‘for’ loop to iterate through an iterable as follows: >>> numbers=[10,20,30,40,50] >>> for num in numbers: print (num) 10 20 30 40 50We can use iter() function to obtain iterator object underlying any iterable. >>> iter('Hello World') <str_iterator object at 0x7f8c11ae2eb8> >>> iter([1,2,3,4]) <list_iterator object at 0x7f8c11ae2208> >>> iter((1,2,3,4)) <tuple_iterator object at 0x7f8c11ae2cc0> >>> iter({1:11,2:22,3:33}) <dict_keyiterator object at 0x7f8c157b9ea8>Iterator object has __next__() method. Every time it is called, it returns next element in iterator stream. When the stream gets exhausted, StopIteration error is raised. >>> numbers=[10,20,30,40,50] >>> it=iter(numbers) >>> it.__next__() 10 >>> next(it) 20 >>> it.__next__() 30 >>> it.__next__() 40 >>> next(it) 50 >>> it.__next__() Traceback (most RECENT call last): File "<pyshell#16>", line 1, in <MODULE> it.__next__() StopIterationRemember that next() function implements __next__() method. Hence next(it) is equivalent to it.__next__() When we use a for/while loop with any iterable, it actually implements iterator protocol as follows: >>> while True: try: num=it.__next__() print (num) except StopIteration: break 10 20 30 40 50A disk file, memory buffer or network stream also acts as an iterator object. Following example shows that each line from a file can be printed using next() function. >>> file=open('csvexample.py') >>> while True: tr KeyboardInterrupt >>> while True: try: line=file.__next__() print (line) except StopIteration: break |
|