python byRef // copy

Question:

I am new to Python (and dont know much about programming anyway), but I remember reading that python generally does not copy values so any statement a = b makes b point to a. If I run

a = 1
b = a
a = 2
print(b)

gives the result 1. Should that not be 2?

Asked By: user1266138

||

Answers:

No, the result should be 1.

Think of the assignment operator (=) as the assignment of a reference.

a = 1  # a references the integer object 1
b = a  # b and a reference the same object
a = 2  # a now references a new object (2)
print b  # prints 1 because you changed what a references, not b

This whole distinction really is most important when dealing with mutable objects such as lists as opposed to immutable objects like int, float and tuple.

Now consider the following code:

a = []  # a references a mutable object
b = a   # b references the same mutable object
b.append(1)  # change b a little bit
print a  # [1] -- because a and b still reference the same object 
         #        which was changed via b.
Answered By: mgilson

When you execute b = a, it makes b refer to the same value a refers to. Then when you execute a = 2, it makes a refer to a new value. b is unaffected.

The rules about assignment in Python:

  1. Assignment simply makes the name refer to the value.

  2. Assignment to a name never affects other names that refer to the old value.

  3. Data is never copied implicitly.

Answered By: Ned Batchelder

You can see what you were expecting with just one small change. The two variables do indeed start out pointing to the same object, and if that object is mutable you can see a change in both places at once.

>>> a = [1]
>>> b = a
>>> a[0] = 2
>>> print b
[2]

What you did with your example was to change a so that it no longer referred to the object 1 but rather to the object 2. That left b still referring to the 1.

Answered By: Mark Ransom

@mgilson has a great answer but I find it a tad harder to grasp. I’m putting this answer in as an attempt to explain it in a different way.

a = 1 # This makes a point to a location in memory where the Integer(1) is located
b = a # This makes b point to the same place.
a = 2 # This makes a point to a different location in memory where Integer(2) is located
print(b) # b still points to the place where Integer(1) was stored, so it prints out 1.
Answered By: Sephallia
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.