0

I am new to Python. I am bit confused about how python function decides if a variable is referred or assigned. I think this determines whether the variable is global or local.

For example,

x = 1 #assignment
y = x + 1 #reference
x[0] = 1 #reference or assignment????
x += 1 #reference or assignment????

Is there any general rule that I don't know?

maxwell
  • 121
  • 3
  • 10
  • http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference This is the best explanation I've found – BCza Nov 26 '14 at 19:48

1 Answers1

0

The key question for global vs local is whether the name is bound by an assignment statement.

x = 1 #assignment
y = x + 1 #reference

right and right.

x[0] = 1 #reference or assignment????

This is a reference to x. This statement is the same effect as x.__setitem__(0, 1). It invokes a method on x. It does not assign to the name x.

x += 1 #reference or assignment????

This is an assignment to x. It has the same effect as x = x.__iadd__(1).

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662