EllaP EllaP - 1 year ago 179
Python Question

How to reverse the elements in a sublist?

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:

def deep_reverse(L)
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):

In the example above, my code would just print
[5,6,7], [3,4], [1,2]
, which is not what i'm trying to accomplish. It's just reversing the order of the lists, the not actual elements in the lists.

What should I add to the code so that it also reverses the order of the elements in a sublist?

[EDIT: my code needs to mutate the list; I don't want it just to print it, it actually needs to change the list.]

Answer Source

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 L).

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):
    for sublist in L:

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download