3

I am confused by python's handling of pointers. For example:

a=[3,4,5]
b=a
a[0]=10
print a

returns [10, 4, 5]

The above would indicate that b and a are pointers to the same location. The issue is what if we say:

a[0]='some other type'

b now equals ['some other type', 4, 5]

This is not the behavior I would expect as python would have to reallocate the memory at the pointer location due to the increase in the size of the type. What exactly is going on here?

2
  • 2
    I don't understand...you made b=a, so both a and b are referring to same memory location?...whatever change you do using a will be the same in b .. Commented Jul 11, 2015 at 5:58
  • please look this link google.co.in/… Commented Jul 11, 2015 at 6:17

2 Answers 2

4
  1. Variables in Python are just reference to memory location of the object being assigned.
  2. Changes made to mutable object does not create a new object

When you do b = a you are actually asking b to refer to location of a and not to the actual object [3, 4, 5]

To explain further:

In [1]: a = [1, 2]    
In [2]: b = a  # b & a point to same list object [1, 2]    
In [3]: b[0] = 9  # As list is mutable the original list is altered & since a is referring to the same list location, now a also changes    
In [4]: print a
[9, 2]    
In [5]: print b
[9, 2]
Sign up to request clarification or add additional context in comments.

Comments

0

Python does not have pointers. Your code creates another variable b, which becomes a reference to a, in other words, it simply becomes another way of referring to a. Anything you do to a is also done to be, since they are both names for the same thing. For more information, see python variables are pointers?.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.