local and global variable usage in Python
<p>I am testing a reverse function. My code is as follow:</p>

<pre><code>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)
</code></pre>

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

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

<p><code>L</code> 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 <code>L</code> in the function to another object. See <a href="http://nedbatchelder.com/text/names.html" rel="nofollow">Ned Batchelder's excellent explanation about Python names</a>.</p>

<p>You could replace all elements <em>in</em> the list <code>L</code> references by assigning to the <code>[:]</code> identity slice instead:</p>

<pre><code>L[:] = new_list[::-1]
</code></pre>

<p>However, mutable sequences like lists have a <a href="https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types" rel="nofollow"><code>list.reverse()</code> method</a>, so you can just reverse the list in-place with that:</p>

<pre><code>L.reverse()
</code></pre>

<p>Do the same for each sublist:</p>

<pre><code>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()
</code></pre>

python list global-variables reverse local-variables