References and copying
danmcleran at yahoo.com
danmcleran at yahoo.com
Fri Jun 9 11:15:18 EDT 2006
> Where can I find a good explanation when does an interpreter copy the
> value, and when does it create the reference.
Any good Python book. I have Learning Python and Programming Python 2nd
edition and they are very good IMO.
> I thought I understand
> it, but I have just typed in following commands:
>
> >>> a=[[1,2],[3,4]]
> >>> b=a[1]
> >>> b=[5,6]
> >>> a
> [[1, 2], [3, 4]]
> >>> b
> [5, 6]
>
> And I don't understand it. I thought, that b will be a reference to a,
> so changing b should change a as well.
No, you've set the name b to reference a slice of a. Slicing a list
always returns a new list.
To change a via b, do this:
a = [[1,2],[3,4]]
b = a
print a
print b
b[1] = [5,6]
print a
print b
More information about the Python-list
mailing list