python list group by first character
list1=['hello','hope','hate','hack','bit','basket','code','come','chess'] What I need is: list2=[['hello','hope','hate','hack'],['bit','basket'],['code','come','chess']] If the first character is the same and is the same group, then sublist it. How can I solve this? You can use itertools.groupby : >>> from itertools import groupby >>> list1 = ['hello','hope','hate','hack','bit','basket','code','come','chess'] >>> [list(g) for k, g in groupby(list1, key=lambda x: x[0])] [['hello', 'hope', 'hate', 'hack'], ['bit', 'basket'], ['code', 'come', 'chess']] Expanding on TerryA's answer: To create a