Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging a list of lists

How do I merge a list of lists?

[['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]

into

['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']

Even better if I can add a value on the beginning and end of each item before merging the lists, like html tags.

i.e., the end result would be:

['<tr>A</tr>', '<tr>B</tr>', '<tr>C</tr>', '<tr>D</tr>', '<tr>E</tr>', '<tr>F</tr>', '<tr>G</tr>', '<tr>H</tr>', '<tr>I</tr>']
like image 602
Steven Matthews Avatar asked Oct 25 '11 20:10

Steven Matthews


2 Answers

Don't use sum(), it is slow for joining lists.

Instead a nested list comprehension will work:

>>> x = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]
>>> [elem for sublist in x for elem in sublist]
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
>>> ['<tr>' + elem + '</tr>' for elem in _]

The advice to use itertools.chain was also good.

like image 185
Raymond Hettinger Avatar answered Sep 28 '22 19:09

Raymond Hettinger


import itertools

print [('<tr>%s</tr>' % x) for x in itertools.chain.from_iterable(l)]

You can use sum, but I think that is kinda ugly because you have to pass the [] parameter. As Raymond points out, it will also be expensive. So don't use sum.

like image 25
Winston Ewert Avatar answered Sep 28 '22 18:09

Winston Ewert