Merging sublists in python

Question:

How do i merge [['a','b','c'],['d','e','f']] to ['a','b','c','d','e','f']?

Asked By: thclpr

||

Answers:

list concatenation is just done with the + operator.

so

total = []
for i in [['a','b','c'],['d','e','f']]:
    total += i

print total
Answered By: will

This would do:

a = [['a','b','c'],['d','e','f']]
reduce(lambda x,y:x+y,a)
Answered By: Sibi

Try:

sum([['a','b','c'], ['d','e','f']], [])

Or longer but faster:

[i for l in [['a', 'b', 'c'], ['d', 'e', 'f']] for i in l]

Or use itertools.chain as @AshwiniChaudhary suggested:

list(itertools.chain(*[['a', 'b', 'c'], ['d', 'e', 'f']]))
Answered By: Hui Zheng
mergedlist = list_letters[0] + list_letters[1]

This assumes you have a list of a static length and you always want to merge the first two

>>> list_letters=[['a','b'],['c','d']]
>>> list_letters[0]+list_letters[1]
['a', 'b', 'c', 'd']
Answered By: Harpal

Using list comprehension:

ar = [['a','b','c'],['d','e','f']]
concat_list = [j for i in ar for j in i]
Answered By: Ketouem

Try the “extend” method of a list object:

 >>> res = []
 >>> for list_to_extend in range(0, 10), range(10, 20):
         res.extend(list_to_extend)
 >>> res
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Or shorter:

>>> res = []
>>> map(res.extend, ([1, 2, 3], [4, 5, 6]))
>>> res
[1, 2, 3, 4, 5, 6]
Answered By: Kiwisauce
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.