Addressing the last element of a list

Bengt Richter bokr at oz.net
Tue Nov 8 11:13:42 CET 2005


On 8 Nov 2005 01:43:43 -0800, "pinkfloydhomer at gmail.com" <pinkfloydhomer at gmail.com> wrote:

>But if lst[42]["pos"] happens to hold an integer value, then
>
>a = lst[42]["pos"]
>
>will _copy_ that integer value into 'a', right? Changing 'a' will not
>change the value at lst[42]["pos"]

Right, but try an example:

 >>> lst = range(42)+[{'pos':123}]+range(43,50)
 >>> lst
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 2
 6, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, {'pos': 123}, 43, 44, 45, 46, 47,
  48, 49]
 >>> lst[41:44]
 [41, {'pos': 123}, 43]
 >>> lst[42]
 {'pos': 123}
 >>> lst[42]['pos']
 123
 >>> a = lst[42]['pos']
 >>> a
 123
 >>> lst[42]['pos']
 123
 >>> id(lst[42]['pos'])
 49421860
 >>> id(a)
 49421860

IOW, a is now an alias for the same 123 immutable integer object as is referred to by the 'pos' key
in the dict which is the 43rd element (index 42) of lst.

Regards,
Bengt Richter



More information about the Python-list mailing list