I know that "".join(list)
converts the list to a string, but what if that list contains a nested list? When I try it returns a TypeError
due to unexpected list type. I'm guessing it's possible with error handling, but so far my attempts have been fruitless.
Asked
Active
Viewed 2,318 times
2

juliomalegria
- 24,229
- 14
- 73
- 89

sundar
- 105
- 1
- 8
-
http://stackoverflow.com/questions/716477/join-list-of-lists-in-python – Matt Ball Mar 07 '12 at 18:46
-
@MДΓΓ БДLL So much rep, and no dup vote? Already out of votes for today? – phihag Mar 07 '12 at 18:48
-
This command is used to concatenate strings. If the objects in the list are not strings (like lists, in your example) you will have to try to convert them to strings like suggested below first. – mohit6up Mar 07 '12 at 18:54
3 Answers
6
You could try something like this:
''.join(''.join(inner) for inner in outer)
That should work, and won't have too much trouble if the outer list contains both Strings and Lists inside of it, ''.join(myString) -> myString
.

g.d.d.c
- 46,865
- 9
- 101
- 111
0
Also you could try this snippet:
from collections import Iterable
ellipsis = type('',(),{'__str__' : lambda self:'...'})()
def flatten(collection,stack = None):
if not stack: stack = set()
if id(collection) in stack:
yield ellipsis
return
for item in collection:
if isinstance(item,Iterable):
stack.add(id(collection))
for subitem in flatten(item,stack):
yield subitem
stack.remove(id(collection))
else: yield item
x = [1,2,[3,4,[5],[[6]],7]]
x.append(x)
>>> print(', '.join(map(str,flatten(x))))
1, 2, 3, 4, 5, 6, 7, ...

Odomontois
- 15,918
- 2
- 36
- 71