Use itertools.groupby() to group your input with a specific key, such as the first letter:
from itertools import groupby from operator import itemgetter for letter, words in groupby(sorted(somelist), key=itemgetter(0)): print letter for word in words: print word print
If your list is already sorted, you can omit the sorted() call. The called itemgetter(0) returns the first letter of each word (character with index 0), and groupby() will return this key plus iterability, consisting only of those elements for which the key remains unchanged. In this case, this means that looping over words gives you all the elements starting with the same character.
Demo:
>>> somelist = ['About', 'Absolutely', 'After', 'Aint', 'Alabama', 'AlabamaBill', 'All', 'Also', 'Amos', 'And', 'Anyhow', 'Are', 'As', 'At', 'Aunt', 'Aw', 'Bedlam', 'Behind', 'Besides', 'Biblical', 'Bill', 'Billgone'] >>> from itertools import groupby >>> from operator import itemgetter >>> >>> for letter, words in groupby(sorted(somelist), key=itemgetter(0)): ... print letter ... for word in words: ... print word ... print ... A About Absolutely After Aint Alabama AlabamaBill All Also Amos And Anyhow Are As At Aunt Aw B Bedlam Behind Besides Biblical Bill Billgone
source share