Iterators and generators

Looping through a list or a dictionary is very simple. Note that, with dictionaries, the iteration is key-based, which is demonstrated in the following example:

for entry in ['alpha', 'bravo', 'charlie', 'delta']:     print (entry) # prints the content of the list, one entry for line a_dict = {1: 'alpha', 2: 'bravo', 3: 'charlie', 4: 'delta'} for key in a_dict:     print (key, a_dict[key]) # Prints: # 1 alpha # 2 bravo # 3 charlie # 4 delta

On the other hand, if you need to iterate through a sequence and generate objects on the fly, you can use a generator. A great advantage of doing this is that you don't have to create and store the complete sequence at the beginning. Instead, you build every object every time the generator ...

Get Python Data Science Essentials - Third Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.