I have a nested list, and I need to reverse every element in the list. But I dont know whether the list is a list of list of list or not.
So example is:
p = [1, [2, 3, [4, [5, 6]]]]
print deep_reverse(p)
#>>> [[[[6, 5], 4], 3, 2], 1]
q = [1, [2,3], 4, [5,6]]
print deep_reverse(q)
#>>> [ [6,5], 4, [3, 2], 1]
What I have so far is:
def is_list(p):
return isinstance(p, list)
def deep_reverse(a):
a.reverse()
for i in a:
if is_list(i):
i.reverse()
print a
It works well for the second test, the q one, but doest work for the first test.
I am not sure do I need use a recursion to loop the whole thing? How can I modify my code? Thanks.
The reason your code doesn’t work is because if
iis a list of lists, you don’tdeep_reversethe lists withini.You only need to change one line of your code to the following: