Error while concatenating nested list string to a list of strings

Question:

I have a nested lists contain string example as

[['abc','abc df','pqr'],['xyz','efg']]

I want to concatenate the this nested list into one list of strings such as

['abc','abc df','pqr','xyz','efg']

like that. i use the the code

all_tokens = sum(text, [])

but its bringing me the error saying

can only concatenate list (not "str") to list

Why its happening like that? how to fix the error? also what are the alternative methods to do the same task?

EDIT

i know iterate through a for loop can manage the same thing. but i am searching for a fast method

Asked By: Nipun Alahakoon

||

Answers:

You can use reduce, it goes through the lists and concatenate them.

l=[['abc','abc df','pqr'],['xyz','efg']]
print reduce(lambda x,y:x+y,l)

Output:

['abc', 'abc df', 'pqr', 'xyz', 'efg']

You can use nested loops in List comprehension as well

print [item for subL in l for item in subL]

You can sum the list, using sum()

print sum(l, [])

You can also use itertools.chain()

from itertools import chain
print list(chain(*l))

It would give the same result.

Answered By: user4179775

Some example code would be good to have, but I assume you have a list of lists you would like to ‘concatenate’ into one list. Here is how it could be done:

a = [['abc','abc df','pqr'],['xyz','efg']]
b = []
for element in a:
    b.extend(element)

It will not check for duplicate elements. To do so, you can use set to make sure each element is present only once:

mylist = list(set(b))
Answered By: Alex

use itertools.chain like so:

from itertools import chain
x = chain.from_iterable([['abc','abc df','pqr'],['xyz','efg']])
# you can also make a list out of it, if you need to
x = list(x)
Answered By: Rusty
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.