2

alist += [4] and alist = alist + [4] are different as the first changes the reference of alist whereas the latter doesn't. I tried this below on IDLE by using id() and it seems like it is correct claim.

Code executed on IDLE (Python 3.6.1)

>>> alist = [1, 2, 3]
>>> id(alist)
50683952
>>> alist += [4]
>>> id(alist)
50683952
>>> alist = alist + [4]
>>> id(alist)
50533080

Here is documentation for id() : https://docs.python.org/3/library/functions.html#id

Is it possible to get reference to memory address programatically, identify whether the location has a list or a dictionary, read the contents and update the content using reference?

NOTE: I found 2 relevant stackoverflow posts but I am not sure if they answer my question.

JRG
  • 4,037
  • 3
  • 23
  • 34
  • 1
    What `id` returns aren't memory locations. You cannot access those with python. In fact, you cannot access it in any language (even C, all you get are the logical addresses). – cs95 Aug 02 '17 at 01:09
  • ah ok, but the documentation says id() is the address of the object in memory. – JRG Aug 02 '17 at 01:11
  • 1
    A misnomer, certainly. It is only an integer giving an _indication_ of the object's reference, which vaguely resembles a memory reference. – cs95 Aug 02 '17 at 01:14
  • I also see no reason to do what you are doing. It seems like the exact definition of an anti-pattern in Python. If you need a unique identifier based on identity, use `id()`. If you need a by-value comparison, use `==`. – Alex Huszagh Aug 02 '17 at 01:21
  • 1
    The fact that `id` returns the memory address is an implementation detail of Cpython – pppery Aug 02 '17 at 01:51

2 Answers2

2

You are trying to do something like in C, with a Dereference operator, such as * , you can read more about it in this question. I'm sure that Python has no support for doing what you are trying to achieve, you have to change your mind paradigm, think different to get the results you want.

As you read, you can "get the memory address" from an object, but you want ever find a way (at least in python 2 - 3) to get the way back

developer_hatch
  • 15,898
  • 3
  • 42
  • 75
2

If you need to check if a Python object is a dict or list, use isinstance. If you need to check if the unique identifier for an object (related to memory address, I believe), use id. If you need to check equality by value, use ==.

There is no reason to do what you are doing right now: everything in Python is a reference-counted, garbage-collected pointer, you should not worry about how this is implemented. In addition to being prone to break version to version, it also is intentionally not exported in the Python API.

If you need the address of a PyObject in the C API, well it's already a pointer (and already done for you). You can use the C API to check if a pointer that is known to be a PyObject is a dict or list accordingly.

Alex Huszagh
  • 13,272
  • 3
  • 39
  • 67