[Tutor] pointers or references to variables or sub-sets of variables query.

Alan Gauld alan.gauld at yahoo.co.uk
Sun Jul 7 04:09:46 EDT 2019


On 07/07/2019 03:39, mhysnm1964 at gmail.com wrote:

> In C, you can use pointers to reference variables, arrays, ETC. In python, I
> do not recall anything specifically that refers to such a capability.

In Python a variable is a name that refers to an object.
Many names can refer to the same object. So in that respect
Python variables are more like pointers than regular C
variables which are a named location in memory.

> Data = [
>   ['2019-01-19','Fred Flintstone',23],
>   ['2019-02-01','Scooby doo', 99]
> ]
> 
> 
> Category = {'under-50':[data[0]], 'over-50':[data[1]]}
> 
> If I understand things correctly with Python. The above will copy the value
> into the list within the key.

No, that is not correct.
It will create a reference to the same data object

So Category['under-50'][0] and Data[0] will both reference
the same list object. Modifying the data through either
variable will affect both because it will be the same
list being modified.

>  Not the memory address of the nested list I am
> referencing. 

It is best to forget all about memory addresses when thinking
about Python. They are irrelevant for the most part..

> Category['under-50'] = [ List1 pointer, List22 pointer, List52 pointer]

That is exactly what happens in Python, as standard.

The usual issue that people have with this is that they modify
the data in one place and are surprised to discover it has
been modified elsewhere too. If that is a problem then you must
explicitly create a copy. But the behaviour that you apparently
want is the default.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list