[what] Iterables and Iterators In Python


Iterables

Iterables are objects that are capable of returning their members one at a time. 

Examples of iterables:

(1) all sequence types (such as list, str, and tuple)

(2) some non-sequence types like dict, file objects

(3) objects of any classes that are defined with an __iter__() method or with a __getitem__() method that implements Sequence semantics.

https://docs.python.org/3/glossary.html#term-iterable

Iterators

Iterators are objects that represent a stream of data. 

Repeated calls to the iterator’s __next__() method (or passing it to the built-in function next()) return successive items in the stream. 

When no more data are available a StopIteration exception is raised instead.

https://docs.python.org/3/glossary.html#term-iterator

# iterables
listName1=["tom","dick","harry"]
# conventional style of fetching an item from collections
for listItem1 in listName1:
  print(listItem1)
  
print("\n====================\n")  
  
# iterators
iterListName1 = iter(listName1)
# streaming approach of fetching an item from collections
# also called lazy-loading
# more efficient for large collections
try:
    while True:
        print(next(iterListName1))
except StopIteration:
    print("Stop iteration")

print("\n====================\n")  

# conventional style of iterItem is also possible
iterListName2 = iter(listName1)
for iterItem1 in iterListName2:
  print(iterItem1)




Post a Comment

0 Comments