2

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.

3
  • stackoverflow.com/questions/716477/join-list-of-lists-in-python Commented Mar 7, 2012 at 18:46
  • @MДΓΓ БДLL So much rep, and no dup vote? Already out of votes for today? Commented Mar 7, 2012 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. Commented Mar 7, 2012 at 18:54

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

5

Well, if the list is nested, simply flatten it beforehand:

>>> import itertools
>>> lst = [['a', 'b'], ['c', 'd']]
>>> ''.join(itertools.chain(*lst))
'abcd'

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.