Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"".join(list) if list contains a nested list in python?

Tags:

python

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.

like image 455
sundar Avatar asked Sep 10 '26 15:09

sundar


2 Answers

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.

like image 120
g.d.d.c Avatar answered Sep 13 '26 08:09

g.d.d.c


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

>>> import itertools
>>> lst = [['a', 'b'], ['c', 'd']]
>>> ''.join(itertools.chain(*lst))
'abcd'
like image 29
phihag Avatar answered Sep 13 '26 08:09

phihag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!