0

I want to make a function that removes any layers of lists in a list

Example

[[[[(1,2)]]],[[(3,4)]]] --> [(1,2),(3,4)]

[(1, 2), [(1, 2)]] -->[(1,2),(1,2)]

Here is my attempt using recursion which didnt work on the second example.

def nolistlist(t): 
    flat_list = []
    for i in t:
        if isinstance(i,list):
            for x in t:   
                if type(x) == list:
                    for y in x:
                        flat_list.append(y)
                else:
                    flat_list.append(x)
            return nolistlist(flat_list)
        else:
            return t 

Anyone that has a simple solution without importing any library? I know the problem but cant come up with a solution. Have been trying to solve this problem for while now. Help would be appreciated!

Che Che
  • 9
  • 1

2 Answers2

3

Another version, without using global variable:

l = [(1, 2), [(1, 2)]]


def flatten(l):
    if isinstance(l, list):
        for v in l:
            yield from flatten(v)
    else:
        yield l

print(list(flatten(l)))

Prints:

[(1, 2), (1, 2)]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

I hate this answer because it relies on a global, but I haven't figured out how to solve it with nested yields yet.

x = [[[[(1,2)]]],[[(3,4)]]] #--> [(1,2),(3,4)]

glist = []
def notlist(z):
    for i in z:
        if isinstance(i,list):
            notlist(i)
        else:
            glist.append(i)
    return glist

print( notlist(x) )
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30