A brief documentation on iterables and iterators in Python.
An iterator is an object that can be iterated, i.e. one can traverse through all of its elements. Iterables are containers that can provide an iterator object.
Examples of iterables are Python lists, Python tuples, Python sets and Python dictionaries. When traversing through these container types in e.g. a for-loop an iterator object is implicitly created. An iterator object can also explicitly be created, using the .iter() method.
Example of “implicit” creation of iterator object from a list container
# declaring a list in Python listObj = [1,2,3] # traversing through list (iterable), implicitly creating and using an iterator object for i in listObj: print(i)
1 2 3
Example of “explicit” creation of iterator object in Python
# creating iterator object from listObj (a list, i.e. an iterable) iteratorObj = iter(listObj) # looping through iterator for i in iteratorObj: print(i)
1 2 3
Data scientist focusing on simulation, optimization and modeling in R, SQL, VBA and Python
Leave a Reply