Home > other >  Reversing a list and all the sublists inside it
Reversing a list and all the sublists inside it

Time:04-05

I have a problem where I'm asked to define a procedure to reverse a list and every sublist in it For example:

p = [1, [2, 3, [4, [5, 6]]]]
print deep_reverse(p)
>>> [[[[6, 5], 4], 3, 2], 1]

The tutor solution was the following:

def is_list(p):
    return isinstance(p, list)
def deep_reverse(p):
    if is_list(p):
        result = []
        for i in range(len(p) - 1, -1, -1):
            result.append(deep_reverse(p[i]))
        return result
    else:
        return p

I’m wondering if it is possible to define a separate procedure to reverse the lists (reverse_list) and implementing it inside the deep_reverse procedure.
I tried doing so, but failed
thanks

CodePudding user response:

Here would be a simpler, IMO more pythonic, version of the code:

def deep_reverse(l):
    if isinstance(l, list):
        return [deep_reverse(e) for e in l[::-1]]
    else:
        return l

or, using a ternary conditional (less explicit IMO):

def deep_reverse(l):
    return [deep_reverse(e) for e in l[::-1]] if isinstance(l, list) else l

example:

deep_reverse([1, [2, 3, [4, [5, 6]]]])
[[[[6, 5], 4], 3, 2], 1]

CodePudding user response:

It is overkill to create a separate function for reversing a list, as there is already a native reversed function and also the [::-1] syntax.

Here is how you can use the reversed function -- which returns an iterator:

def deep_reverse(lst):
    return list(map(deep_reverse, reversed(lst))) if isinstance(lst, list) else lst
  • Related