Converting a list of lists into a list of strings


In Python how do I convert:

list01 = [ ['a', 'b', 'c'], ['i', 'j', 'k'], ['x', 'y', 'z'] ]


list02 = [ 'abc', 'ijk', 'xyz']
Asked By: Mazzone



Use str.join and a list comprehension:

>>> list01 = [ ['a', 'b', 'c'], ['i', 'j', 'k'], ['x', 'y', 'z'] ]
>>> [''.join(x) for x in list01]
['abc', 'ijk', 'xyz']
Answered By: user2555451

Using map:

map(''.join, list01)

Or with a list comprehension:

[''.join(x) for x in list01]

Both output:

['abc', 'ijk', 'xyz']

Note that in Python 3, map returns a map object instead of a list. If you do need a list, you can wrap it in list(map(...)), but at that point a list comprehension is more clear.

Answered By: mhlester
>>> map(''.join, list01)
['abc', 'ijk', 'xyz']
Answered By: moliware

You can use join to implode the elements in a string and then append, if you don’t want to use map.

# Your list
someList = [ ['a', 'b', 'c'], ['i', 'j', 'k'], ['x', 'y', 'z'] ]
implodeList = []

# make an iteration with for in
for item in someList:

# printing your new list
['abc', 'ijk', 'xyz']
Answered By: afym
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.