The recursive solution is pretty trivial, just recursing through an array modifying each subarray:
arr= [[2, 1], [4, 3]] def reve(l): # if we have recursed across all sub arrays just return empty list if not l: return [] # else reverse the first current sublist l[0] and recurse on the remaining sublists return [l[0][::-1]] + reve(l[1:]) print(reve(arr)) [[1, 2], [3, 4]]
What can I write briefly:
def reve(l): return [l[0][::-1]] + reve(l[1:]) if l else []
If you want it in place:
arr = [[1, 2, 3, 4], [1, 2, 3, 4]] def reve(l): if not l: return
Output:
[[4, 3, 2, 1], [4, 3, 2, 1]]
And finally, we can achieve what you want in place without slicing at all, using iter with the special __length__hint method:
def reve(l): if l.__length_hint__() == 0: return sub = next(l) sub.reverse() return reve(l) reve(iter(arr)) print(arr)
Output:
[[4, 3, 2, 1], [4, 3, 2, 1]]