user2534382
user2534382

Reputation: 11

Python merging sublist

I've got the following list : [['a','b','c'],['d','e'],['f','g','h','i',j]]

I would like a list like this : ['abc','de','fghij']

How is it possible?

[Edit] : in fact, my list could have strings and numbers,

l = [[1,2,3],[4,5,6], [7], [8,'a']]

and would be :

l = [123,456, 7, 8a]

thx to all,

Upvotes: 0

Views: 1813

Answers (2)

oleg
oleg

Reputation: 4182

you can apply ''.join method for all sublists. This can be done either using map function or using list comprehensions

map function runs function passed as first argument to all elements of iterable object

initial = ['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i', 'j']]
result = map(''.join, initial)

also one can use list comprehension

initial = ['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i', 'j']]
result = [''.join(sublist) for sublist in initial]

Upvotes: 4

devnull
devnull

Reputation: 123668

Try

>>> L = [['a','b','c'],['d','e'],['f','g','h','i','j']]
>>> [''.join(x) for x in L]
['abc', 'de', 'fghij']

Upvotes: 4

Related Questions