Mazzone
Mazzone

Reputation: 431

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'] ]

into

list02 = [ 'abc', 'ijk', 'xyz']

Upvotes: 10

Views: 28824

Answers (4)

afym
afym

Reputation: 532

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:
    implodeList.append(''.join(item))

# printing your new list
print(implodeList)
['abc', 'ijk', 'xyz']

Upvotes: 1

moliware
moliware

Reputation: 10288

>>> map(''.join, list01)
['abc', 'ijk', 'xyz']

Upvotes: 2

mhlester
mhlester

Reputation: 23251

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.

Upvotes: 21

user2555451
user2555451

Reputation:

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']
>>>

Upvotes: 3

Related Questions