-2

I am looking to get one list of multiple nested list:

list1 = [[1,2],[3,[4,5]],6,[7]] Output --> [1,2,3,4,5,6,7]

I just joined Stack overflow and hence couldn't post my answer to a similar trending question like this.

Hence I am posting my answer here which I thought of to be the fastest, let me know if anyone gets a better solution. Meanwhile, people can refer this for their disposal:

a = str(list1)  #Convert list to String
a = a.replace('[','')
a = a.replace(']','') # remove '['&']' from the list use specific brackets for other data structures
# in case of dictionary replace ':' with ','
b=a.split(',')  # Split the string at ','
d = [int(x) for x in b]

This should be able to do it for any level of complex list..

Dnyanraj Nimbalkar aka Samrat

Chris
  • 29,127
  • 3
  • 28
  • 51
  • 1
    Please go through the [intro tour](https://stackoverflow.com/tour), the [help center](https://stackoverflow.com/help) and [how to ask a good question](https://stackoverflow.com/help/how-to-ask) to see how this site works and to help you improve your current and future questions, which can help you get better answers. We expect you to do appropriate research before posting a question here. Using the title of your question easily brings up solutions. – Prune Feb 02 '21 at 05:56

1 Answers1

0

Try this:

list_ = [[1,2],[3,[4,5]],6,[7]]

def flatten_list(input_, output):
    for item in input_:
        if isinstance(item, list):
            flatten_list(input_ = item, output = output)
        else:
            output.append(item)
    return output

output = flatten_list(input_ = list_, output = list())
print(output)

>>>[1, 2, 3, 4, 5, 6, 7]
sarartur
  • 1,178
  • 1
  • 4
  • 13
  • Yes.. I did go through this one.. which one would run faster this or mine?? – sam rules Feb 02 '21 at 05:42
  • I do not know which one is faster, but converting list to string and flattening it that way seems like a poor practice. For instance, the function will work for list containing any items, while your code will fail if for instance one of the items is a string and contains a ```'['``` or ```','``` character. – sarartur Feb 02 '21 at 05:48
  • Aye.... you are right.. Thanks – sam rules Feb 03 '21 at 01:11