Get a pointer to a list element

后端 未结 2 922
旧巷少年郎
旧巷少年郎 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条回答
  •  余生分开走
    2020-12-09 13:20

    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
    

提交回复
热议问题