• Register

You mean you’ve got a reference to a value you know is stored in a list and you’d like to get the index under which it’s stored?

I’m afraid you’ll have to go through the list and check, for each item, if it is the value. So something like this:

def get_index(lst, val): 
    for index, item in enumerate(lst): 
        if item is val: return index 
    return None  # you were wrong, the value isn't there 

Values are referenced in Python; the is operator checks if the arguments reference the same value.

Python doesn’t have any pointers (and references don’t support any sort of pointer arithmetics). In C/C++, for example, you could simply take the address of the value and subtract the address of the (plain) array from it, producing the index directly (assuming that the value really is stored in the array). But that’s because C/C++ (plain) arrays really are just continuous pieces of memory, storing the values one-by-one, each having the same size. Python’s list are not implemented like that, the values generally don’t have the same sizes and you don’t have access to any information where exactly the data objects are; no addresses with which you could do any such arithmetical operations anyway.

Do note one thing, though. If you need the above, you’ve designed your data structure poorly. No such thing should be required if you design it right; you should handle the values via references, not indices in a list (if it can change in time). So you should never really need such an inefficient operation.

1,760 points
6 1