I was wondering if it was possible to get a \"pointer\" to an element in a python list. That way, I would be able to access my element directly without needing to know my el
element = mylist[0]
already works if you don't need to change the element or if element
is a mutable object.
Immutable objects such as int
objects in Python you can not change. Moreover, you can refer to the same object using multiple names in Python e.g., sys.getrefcount(1)
is ~2000 in a fresh REPL on my system. Naturally, you don't want 1
to mean 2
all of a sudden in all these places.
If you want to change an object later then it should be mutable e.g., if mylist[0] == [1]
then to change the value, you could set element[0] = 2
. A custom object instead of the
[1]
list could be more appropriate for a specific application.
As an alternative, you could use a dictionary (or other namespace objects such as types.SimpleNamespace
) instead of the mylist
list. Then to change the item, reference it by its name: mydict["a"] = 2
.
There's no concept of pointers on python (at least that I'm aware of).
In case you are saving objects inside your list, you can simply keep a reference to that object.
In the case you are saving primitive values into your list, the approach I would take is to make a wrapper object around the value/values and keep a reference of that object to use it later without having to access the list. This way your wrapper is working as a mutable object and can be modified no matter from where you are accesing it.
An example:
class FooWrapper(object):
def __init__(self, value):
self.value = value
# save an object into a list
l = []
obj = FooWrapper(5)
l.append(obj)
# add another object, so the initial object is shifted
l.insert(0, FooWrapper(1))
# change the value of the initial object
obj.value = 3
print l[1].value # prints 3 since it's still the same reference