Home > database >  How can I create a list that is made up of other lists inside using recursion
How can I create a list that is made up of other lists inside using recursion

Time:04-05

Example: I have this list [2,3,[1,2]] and I want that my final list is [2,3,1,2].

But i also have these kinds of list, [1,(2,[2,3])] and i need to leave it in this form [1,2,3,2,3].

Does anyone know how to do this. It would be a great help.

thanks

CodePudding user response:

So if I understood correctly, what you want to do is create a list of all of the elements of a list and its sublists in order? Frankly, sounds like a terrible idea, but it is quite doable by recursion:

def elementlist(input, output = []):
    for element in input:
        if not isinstance(element,(tuple,list)):
            output.append(element)
        else:
            elementlist(element,output)
    return output

list1 = [1,(2,[2,3,(2,3)])]
output = elementlist(list1)
print(output)

The basic idea with this solution is to go through the list adding its elements to the output list, unless it's either a list or a tuple, in which case it will be sent to a deeper recursion level to fetch its individual elements.

CodePudding user response:

You can use try and except instead of using conditionals and type checking -

def recur(t):
  try:
    for x in t:
      yield from recur(x)
  except:
    yield t
    
print(list(recur([1,(2,[2,3])])))
[1,2,2,3]
  • Related