Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing elements of a list vs changing the list itself

I have a question about the name scope of variables, I've tried to find the answer here and I got a similar one but still little confused here Function changes list values and not variable values in Python

So the code is as follows:

position = [50, 50]

# Handler for timer
def tick():
    x = random.randrange(0, width)
    y = random.randrange(0, height)
    position[0] = x
    position[1] = y

Here why don't I need to add "global position" in order to change elements of the variable position?

like image 538
Enkri_ Avatar asked Dec 10 '25 10:12

Enkri_


1 Answers

Adding global position would only be necessary if you were assigning the global position variable to refer to a new list (without the global declaration, position would written into the locals for the function).

In your situation, all you are doing is looking up the global variable position to find which list it refers to. Then you're updating that list in-place.

Here is a Python tutor visualization that shows all the variations (assign to a local, assign to a global, update a list referred to by a global).

Also, have a look at Ned Batchelder's nice blog post that fully explains python's pass-by-object mechanism.

like image 198
Raymond Hettinger Avatar answered Dec 13 '25 11:12

Raymond Hettinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!