Skip to content
Advertisement

Printing list items by group in python

I’m still new to Python. I have similar list to the below list:

items = [[4, 'A'], [4, 'B'], [5, 'C'], [5, 'D'], [5, 'E'], [6, 'F'], [6, 'G']]

I’m trying to print it by grouping the first item together and get something like this:

JavaScript

How do I do this?

Advertisement

Answer

You can use itertools.groupby and operator.itemgetter:

JavaScript

If you want to do this without importing anything:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement