0

I'm a beginner and I want to write a program that turns:

L=[1,3,[5,[2,6],7],[4,8,[9,10]]]

to:

L=[1,2,3,4,5,6,7,8,9,10]

I wrote this function but I do not know what condition to write to recognize whether it is a list variable or not

def f(n):
    a=[]
    for i in n :
        if i==list :
           return f(i)
        else:
            a.append(i)
    return a

If you have a better solution to this problem or you know how to write this condition please help me

Pedro Maia
  • 2,666
  • 1
  • 5
  • 20
  • 2
    What are you trying to do ? please, explain what `f` is expected to perform ? – Alexandre B. Dec 29 '21 at 14:53
  • Does this answer your question? [What is the fastest way to flatten arbitrarily nested lists in Python?](https://stackoverflow.com/questions/10823877/what-is-the-fastest-way-to-flatten-arbitrarily-nested-lists-in-python) – Maurice Meyer Dec 29 '21 at 15:04

3 Answers3

1

You are trying to use recursion which is a great start.

What you are missing is checking the type of item, you can do this in your condition with type(i) and check against the list type like type(i) == list and iterate it then

Also, you cant declare your output variable inside the function as it will get cleaned every time, so pull it out.

Lastly, why do we use recursion - because the levels of nesting cannot be predetermined based on your question.

Working code below

list1 = [1,3,[5,[2,6],7],[4,8,[9,10]]]
result=[]
def flatList(l):
    for i in l:
        if type(i) == list:
            flatList(i)
        else:
            result.append(i)
            
flatList(list1)
print(result)
Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47
0

While looping through n, you can check if an item is a list by doing:

if type(i) is list:
   # do something for list
Jerven Clark
  • 1,191
  • 2
  • 13
  • 26
0

Use isinstance and list.extend:

def f(n):
    a=[]
    for i in n :
        if isinstance(i,list):
            a.extend(f(i))
        else:
            a.append(i)
    return a

That only works for lists, if you want any iterable use collections.Iterable:

import collections


# ...
        if isinstance(i,collections.Iterable):
>>> l = [1,3,[5,[2,6],7],[4,8,[9,10]]]
>>> f(l)
[1, 3, 5, 2, 6, 7, 4, 8, 9, 10]
Pedro Maia
  • 2,666
  • 1
  • 5
  • 20