Search⌘ K
AI Features

groupby(), islice() and starmap()

Explore how to use Python's itertools module functions groupby, islice, and starmap for advanced iterator and data manipulation. Understand how groupby groups sorted data, how islice slices iterators by index, and how starmap applies functions to iterable elements. Gain practical skills with examples to enhance your Python programming.

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 actually loop over the iterator returned by groupby which gives us the key and the group. Then we loop over the group and print out what’s in it.

Just for ...