I'm trying to create a function that reverses the order of the elements in a list, and also reverses the elements in a sublist. for example:
For example, if L = [[1, 2], [3, 4], [5, 6, 7]] then deep_reverse(L) mutates L to be [[7, 6, 5], [4, 3], [2, 1]]
I figured out how to reverse the order of one list, but I am having troubles with reversing the order of elements in a sublist. This is what I have so far:
assumes L is a list of lists whose elements are ints
Mutates L such that it reverses its elements and also
reverses the order of the int elements in every element of L.
It does not return anything.
for i in reversed(L):
[5,6,7], [3,4], [1,2]
This looks very familiar :). I'm not going to give the whole working solution but here are some tips:
As you know, there are two steps, reverse each sub-list and then reverse the outer list (in place, without making a new list, so it will mutate the global
So you can loop through the outer list, and mutate each sub-list:
for i in range(len(L)): # if L[i] is a list: # reverse with [::-1] and update L[i] to the reversed version # reverse the outer list L, list.reverse() will operate in-place on L
Now remember, if you loop through the list like this:
for item in list: item = 'xxx'
You can't change
item with the above code.
item is a placeholder value, so changing it doesn't actually modify the list.
You instead need to index the item in
L, and enumerate can help with this, or you can use the less-preffered
range(len()) as above.
for i, item in enumerate(L): # do something with L[i] L[i] = 'something'
Edit: since there is so much confusion over this, I'll go ahead and post a working solution based on Stefan Pochmann's very elegant answer:
def deep_reverse(L): L.reverse() for sublist in L: sublist.reverse()
Notice there is no return statement, and no print statement. This will correctly modify
L in place. You cannot reassign
L inside the function because then it will just create a new local version of
L, and it will not modify the global
L. You can use
list.reverse() to modify
L in place which is necessary based on the specifications.