Kobayashi Tomoyo Kobayashi Tomoyo - 1 year ago 121
Python Question

local and global variable usage in Python

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]]

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

Answer Source

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:


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:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download