Search code examples
pythonlistconcatenation

Error while concatenating nested list string to a list of strings


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


Solution

  • 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.