Sunday, August 17, 2014

[Python] Understanding iterators and iterables


Hope this note can help not only me  understand iterators and  iterable in Python 3.X.

Some good sources where explanation could be found:


Remarks
Any Python object can be "iterable", which means it can provide a stream of values. An iterable can be used in a for loop
Saing more precise: iterable produce an iterator, itearator produce stream of values
An iterable in Python is any value that can provide a stream of values. Lists , dicts, strings are iterables.
Every iterable type provides it's own iterator type:

lists - list iterators, 
dicts - dict iterators, etc..


 data = ['say' , 134 , 'words']  
 # Lists => elements  
 iter(data)  
 # <list_iterator object at 0x7f3ca04fcb00>  
 word = "morning"  
 # Strings => Characters  
 it = iter(word)  
 # <str_iterator at 0x7f3ca04fc8d0>  
 data_struct = {'age' : 12, 'color' : 'red' , 'isempty' : True}  
 # Dicts => Keys  
 iter(data_struct)  
 # <dict_keyiterator at 0x7f3ca0289688>  
 # Passed to iter() dicts produce key iterators,   
 # so it's possible to pass dict to max() function to get max of all keys.  
 max(data_struct)  
 # 'isempty'  
 f = open('find_friends.ipynb')  
 # Files => Rows  
 iter(f)  
 # <_io.TextIOWrapper name='find_friends.ipynb' mode='r' encoding='UTF-8'>  
 next(iter(iter(iter(iter(data)))))  

The most interesting point that iterable could be passed as argument to max() func for example. (generally to any built in function which accepts as argument an iterable) And the result of func evaluation depends on iterable type, so passing dict iterable to max will produce max key value in dictionary. Also list of keys could be generated in this way.

 max(data_struct) # 'isempty'   
 list(data_struct) # ['age', 'isempty', 'color']  

The most advanced ways if using and understanding of iterables are generators which produce stream if values, and making objects iterable by adding _itter__() method.

Hope, I'll write some notes about these topics later on.

No comments:

Post a Comment