Reputation: 1
I have a nested list, and I need to reverse every element in the list.
Below is the example :
L = [[0, 1, 2], [1, 2, 3]]
Expected Output :
L = [[3, 2, 1], [2, 1, 0]]
I tried with the below piece of code, it works individually but when I am putting this code within function, then the list is not getting updated.
L = [list(reversed(row)) for row in L]
L.reverse()
This code works, and the List "L" is getting updated. But when I put this code in function
def deep_rev(L):
L = [list(reversed(row)) for row in L]
L.reverse()
L = [[0, 1, 2], [1, 2, 3]]
deep_rev(L)
print(L)
This is returning the same list = [[0,1,2],[1,2,3]]
Can anyone please help me in this regard, why in function this is not working?
Upvotes: 0
Views: 984
Reputation: 11
This is the solution I find out using recursion:
l=[[0, 1, 2], [1, 2, 3]]
def treereverse(l):
l.reverse()
for x in l:
if isinstance(x,list):
treereverse(x)
return l
print(treereverse(l))
Upvotes: 1
Reputation: 2050
deep_rev(L)
modifies one local list, its scope is inside this function. Either make one deep copy of the list or return the reversed list.
Upvotes: 0
Reputation: 23443
def deep_rev(l):
l = [list(reversed(row)) for row in l]
l.reverse()
return l
l = [[0, 1, 2], [1, 2, 3]]
l = deep_rev(l)
print(l)
output
[[3, 2, 1], [2, 1, 0]]
Upvotes: 0
Reputation: 104702
Your current code creates a new list, rather than modifying the exiting list in place. You can make it work, just get rid of the list comprehension and do in-place reversals for the inner lists too:
def deep_rev(L):
for inner in L:
inner.reverse()
L.reverse()
If you want to support more than two levels of nesting, you could recursively call deep_rev
on the inner
lists, rather than just reversing them as I did above. You'd need to check if the values were lists or not, so you'd have a base case.
Upvotes: 1
Reputation: 82889
With L = ...
you are assigning a new value to the parameter L
within the function, without modifying the original list. Instead, you can use L[:] = ...
to replace all the elements in the original list with the values from the new list.
def deep_rev(L):
L[:] = [list(reversed(row)) for row in reversed(L)]
L = [[0, 1, 2], [1, 2, 3]]
deep_rev(L)
print(L) # [[3, 2, 1], [2, 1, 0]]
Upvotes: 0
Reputation: 2159
This Code works for your problem,
L = [[0, 1, 2], [1, 2, 3]]
b=list(reversed(L))
q=[]
for i in b:
q.append(list(reversed(i)))
print q
Output:-
[[3, 2, 1], [2, 1, 0]]
Upvotes: 0