Get a pointer to a list element

后端 未结 2 911
旧巷少年郎
旧巷少年郎 2020-12-09 13:06

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

2条回答
  •  萌比男神i
    2020-12-09 13:08

    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.

提交回复
热议问题