Merging sublists in python
Question:
How do i merge [['a','b','c'],['d','e','f']]
to ['a','b','c','d','e','f']
?
Answers:
list concatenation is just done with the +
operator.
so
total = []
for i in [['a','b','c'],['d','e','f']]:
total += i
print total
This would do:
a = [['a','b','c'],['d','e','f']]
reduce(lambda x,y:x+y,a)
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']]))
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']
Using list comprehension:
ar = [['a','b','c'],['d','e','f']]
concat_list = [j for i in ar for j in i]
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]
How do i merge [['a','b','c'],['d','e','f']]
to ['a','b','c','d','e','f']
?
list concatenation is just done with the +
operator.
so
total = []
for i in [['a','b','c'],['d','e','f']]:
total += i
print total
This would do:
a = [['a','b','c'],['d','e','f']]
reduce(lambda x,y:x+y,a)
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']]))
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']
Using list comprehension:
ar = [['a','b','c'],['d','e','f']]
concat_list = [j for i in ar for j in i]
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]