AI Features

groupby(), islice() and starmap()

Let's figure out the iterators that do not terminate. i.e. groupby(), islice() and starmap().

groupby(iterable, key=None)

The groupby iterator will return consecutive keys and groups from your iterable. This one is kind of hard to wrap our heads around without seeing an example. So let’s take a look at one!

Python 3.5
from itertools import groupby
vehicles = [('Ford', 'Taurus'), ('Dodge', 'Durango'),
('Chevrolet', 'Cobalt'), ('Ford', 'F150'),
('Dodge', 'Charger'), ('Ford', 'GT')]
sorted_vehicles = sorted(vehicles)
for key, group in groupby(sorted_vehicles, lambda make: make[0]):
for make, model in group:
print('{model} is made by {make}'.format(model=model,
make=make))
print ("**** END OF GROUP ***\n")

Here we import groupby and then create a list of tuples. Then we sort the data so it makes more sense when we output it and it also let’s groupby actually group items correctly. Next we ...