Search code examples
pythonlistreversenested-lists

reversing a nested list in python


Hello I am trying to convert nested lists in reverse order .

here is my code :

def reverse_(items):
     items =  items[::-1]
        new_l = []
        for item in items:
            if type(item) == list:
                item.reverse()
                new_l.append(item)
            else:
                new_l.append(item)
        return new_l
  1. print(reverse_reversed([1, [2, 3, 4, 'yeah'], 5] )) returns : [5, ['yeah', 4, 3, 2], 1] which is correct

  2. but print(reverse_reversed([42, [99, [17, [33, ['boo!']]]]]) returns : [[[17, [33, ['boo!']]], 99], 42] which should be this : [[[[['boo!'], 33], 17], 99], 42]


Solution

  • It looks like you want to reverse lists recursively not just once nested. That means you need to make a recursive function call, i.e. it needs to call itself.

    def recursive_reversed(items):
        if isinstance(items, list):
            return [recursive_reversed(item) for item in reversed(items)]
        return items
    

    Notes:

    1. I used an isinstance check instead of type(item) ==. This is usually what you want, and it means subclasses of list will be reversed too (although they will be regular lists).
    2. No extra copy is made: reversed iterates over the original list in reverse order.
    3. Nothing is reversed in place: if you look at the contents of your original list after calling your implementation, you will see its sublists will have been reversed as well.
    4. I used a list comprehension which is generally preferred over "create an empty list, loop over something else, appending something to that list each iteration".
    5. My function calls itself as a form of divide and conquer.