How do I concatenate a list such as this:
buttons = [[['a','b','c'], '2'], [['d','e','f'], '3']]
into
buttons = [[['a','b','c','2'], ['d','e','f','3']]]
I tried accessing three indexes and concatenating but it didn't work:
buttons[0][1]
How do I concatenate a list such as this:
buttons = [[['a','b','c'], '2'], [['d','e','f'], '3']]
into
buttons = [[['a','b','c','2'], ['d','e','f','3']]]
I tried accessing three indexes and concatenating but it didn't work:
buttons[0][1]
One way is to unpack each element inside a list comprehension and concatenate the two parts:
>>> buttons = [[['a','b','c'], '2'], [['d','e','f'], '3']]
>>> [x + [y] for x, y in buttons]
[['a', 'b', 'c', '2'], ['d', 'e', 'f', '3']]
This works because for each sublist has two elements; the first element is assigned to x
, the second element is assigned to y
. For example, for the first sublist in buttons
we have:
x, y = [['a','b','c'], '2']
So then:
>>> x
['a','b','c']
>>> y
'2'
These two parts are then joined together like this:
x + [y] == ['a', 'b', 'c'] + ['2'] == ['a', 'b', 'c', '2']
>>> import itertools
>>> l = [[['a','b','c'], '2'], [['d','e','f'], '3']]
>>> [list(itertools.chain.from_iterable(i)) for i in l]
[['a', 'b', 'c', '2'], ['d', 'e', 'f', '3']]