Reputation: 431
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
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
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
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