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?

Joesh
  • 67
  • 6
  • 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` .. – Iron Fist Jul 11 '15 at 05:58
  • please look this link https://www.google.co.in/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=python%20variable%20memory – Aslam Khan Jul 11 '15 at 06:17

2 Answers2

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]
geetha ar
  • 136
  • 5
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?.

Community
  • 1
  • 1
Erik Godard
  • 5,930
  • 6
  • 30
  • 33