-1

Just a simple code below:

import numpy as np
x=np.array([1,2])
y=[1,2]
L=1

def set_L(x,y,L):
    x[0]+=1
    y[0]+=1
    L+=1
    print(id(x))
    print(id(y))
    print(id(L))

I found that array x and list y is the same in the function set_L(), does this mean by default list and array are global variables? however variable L is not global in the function set_L(). I am confusing that why Python is designed like this?

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Liang Xiao
  • 21
  • 3
  • You can find the answer in the duplicate – raul.vila Apr 16 '18 at 07:11
  • The difference is one of mutability. – hpaulj Apr 16 '18 at 07:25
  • @hpaulj while mutability can affect the consequences, it is irrelevant with regards to scope and the semantics of assignment – juanpa.arrivillaga Apr 16 '18 at 07:27
  • This question conflates two things - variable scope, and how `+=` modifies an object. Arrays and lists are mutable and can change without changing `id`, a scalar is not. `id(L)` is the `id` of its value, `id(1)` or `id(2)` (and in Cython small positive integers have a unique id). – hpaulj Apr 16 '18 at 16:12

1 Answers1

0

x[0]+=1 and y[0]+=1 just modify the existing object, while L+=1 is an assignment and creates a new local reference. See https://stackoverflow.com/a/11867500/7662112

Kris
  • 1,358
  • 13
  • 24