Joining elements of a list if those elements are in between two whitespaces Joining elements of a list if those elements are in between two whitespaces python python

Joining elements of a list if those elements are in between two whitespaces


Using itertools.groupby:

from itertools import groupbyl = ['assembly', '', 'py', 'tho', 'n', '', 'ja', 'va', '', 'rub', 'y', '', 'java', 'script', '', 'c++']new_l = [''.join(g) for k, g in groupby(l, key = bool) if k]

Output:

['assembly', 'python', 'java', 'ruby', 'javascript', 'c++']


This is awful and hacky, but

lambda b:lambda l:''.join(i or b for i in l).split(b)

can take any string you can guarantee is not contained in the concatenation of the list, and return a function doing what you want. Of course, you probably want to only use this once or twice for your specific situation, so, if you can guarantee that no element of the list contains a space, it might look more like:

a = ['assembly', '', 'py', 'tho', 'n', '', 'ja', 'va', '', 'rub', 'y', '', 'java', 'script', '', 'c++']a = ''.join(i or ' ' for i in a).split(' ')


If you can't or don't want to use itertools:

l = ['assembly', '', 'py', 'tho', 'n', '', 'ja', 'va', '', 'rub', 'y', '', 'java', 'script', '', 'c++']l_new = []combined = ""for idx, s in enumerate(l):    if s != "":        combined += s        if idx == len(l)-1:            l_new.append(combined)    else:        l_new.append(combined)        combined = ""