infinite_aventura
infinite_aventura

Reputation:

Join certain elements in list of lists

Let's say I have a list that looks like this:

lst = [['a','b','c','d'],['e','f','g','h'],['i','j','k','l']]

Can I join the first two elements in each list within lst, such that the output would look like this:

new_list = [['ab','c','d'],['ef','g','h'],['ij','k','l']]

If this was a flat list, I would write lst[0:2] = [' '.join(lst[0:2])]. I try to nest this code with a list comprehension:

new_list = [[''.join(x[0:2]) for x[0:2] in group] for group in lst]

But I do not get the desired output. Does anyone know what is wrong with my code here and how I accomplish the output above?

Upvotes: 0

Views: 40

Answers (2)

hilberts_drinking_problem
hilberts_drinking_problem

Reputation: 11602

As a slight variation on @not_speshal's answer, you could use list comprehension with a splat operator:

lst = [['a','b','c','d'],['e','f','g','h'],['i','j','k','l']]
res = [[a + b, *rest] for a, b, *rest in lst]

Upvotes: 1

not_speshal
not_speshal

Reputation: 23146

Use list comprehension:

>>> [["".join(l[:2])]+l[2:] for l in lst]
[['ab', 'c', 'd'], ['ef', 'g', 'h'], ['ij', 'k', 'l']]

Upvotes: 1

Related Questions