Search code examples
pythonstringpython-itertools

How can I use python itertools.groupby() to group a list of strings by their first character?


I have a list of strings similar to this list:

tags = ('apples', 'apricots', 'oranges', 'pears', 'peaches')

How should I go about grouping this list by the first character in each string using itertools.groupby()? How should I supply the 'key' argument required by itertools.groupby()?


Solution

  • groupby(sorted(tags), key=operator.itemgetter(0))