0

I am testing a reverse function. My code is as follow:

def deep_reverse(L):

    new_list = []
    for element in L:
        new_list += [element[::-1]]
    L = new_list[::-1]


L = [[1, 2], [3, 4], [5, 6, 7]]
deep_reverse(L)
print(L)

I expect my output L can be like [[7, 6, 5], [4, 3], [2, 1]], but it only works inside my function.

I wasn't able to change it in the global variable. How can I make it happen? Thank you

1 Answer 1

1

L is just a local variable, and assigning a new object to it won't change the original list; all it does is point the name L in the function to another object. See Ned Batchelder's excellent explanation about Python names.

You could replace all elements in the list L references by assigning to the [:] identity slice instead:

L[:] = new_list[::-1]

However, mutable sequences like lists have a list.reverse() method, so you can just reverse the list in-place with that:

L.reverse()

Do the same for each sublist:

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 element in L:
        element.reverse()
    L.reverse()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. It helps me a lot with your explanation!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.