making a flat list out of a list of lists where the elements are strings

Question:

I know a similar question was asked here Making a flat list out of list of lists in Python

But when the elements of the lists are strings, this method does not cut it:

arr = [['i', 'dont'], 'hi']
[item for sublist in arr for item in sublist]
>>['i', 'dont', 'h', 'i']

what I need is:

["I", "dont", "hi"]

thx

Asked By: user1452494

||

Answers:

I know there is a way to do it using your method, but I find that not too readable.

def outlist(li, flatlist):
    if isinstance(li, str):
        flatlist.append(li)
    elif len(li) > 1:
        for i in li:
            outlist(i, flatlist)

flatlist = []
outlist([['test', 'test2'], 'test3'], flatlist)
print(flatlist)
Answered By: beiller

Modify arr so that all top-level strings become enclosed in a list. Then the usual list flattening methods will work properly.

arr = [['i', 'dont'], 'hi']
arr = [[item] if isinstance(item, str) else item for item in arr]
#arr is now [['i', 'dont'], ['hi']]
print [item for sublist in arr for item in sublist]

Result:

['i', 'dont', 'hi']
Answered By: Kevin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.