0

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

2 Answers2

0

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.

Otto Hanski
  • 382
  • 1
  • 6
  • Not quite. I actually have to use recursion to solve this, but what I am looking for is a function that expands all the elements within the list. If the elements are in tuple i need to expand that as well. For example [2,[1,2]] it is only [2,1,2] but if i have a list like [4,3,[2,1,(2,(8,9)]], the answer should be [4,3,2,1,8,9,8,9] because the numbers that are already in simple values remain the same but the ones in tuple expand. Another ex: [2,(3,(4,0))] should be [2,4,0,4,0,4,0]. – jose antonio castro Apr 05 '22 at 00:43
  • Then you should add a check for whether the element being handled is an instance of tuple that should be expanded and expand it if that's the case. This is starting to sound more and more like a homework exercise, so I'll let you figure that part out on your own. – Otto Hanski Apr 05 '22 at 05:42
0

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]
Mulan
  • 129,518
  • 31
  • 228
  • 259