Python Forum
how to refer to a subset of a list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: how to refer to a subset of a list (/thread-36088.html)



how to refer to a subset of a list - Skaperen - Jan-15-2022

i have a function that is given a list and it stores a special value into the first position (index 0) of that list.
def store_special_value(where_to_store):
    ...
    if isinstance(where_to_store,list):
        where_to_store[0] = special_value
    return
i want to call that function and put that value into the n-th element a list:
def main(args)
    ...
    target = []
    ...
    temp_list = [None]
    store_special_value(temp_list)
    target[n] = temp_list[0]
    ...
my question is: is there a more direct way to do this without using the temporary list? that would mean a list reference that refers to a subset of an existing list (target) but operates as if it were a whole list. list slicing creates a new list instead of referring to an existing given list, so that is not a solution. is there a way to make a subset reference like that?

i do have a real use case for this, which is more complicated, but, i prefer to work with a minimal example case, to determine a more general use solution.


RE: how to refer to a subset of a list - BashBedlam - Jan-15-2022

Do you mean like this?
special_value = 13
my_list = [1, 2, 3, 4, 5]
my_list.insert (2, special_value)
print (my_list)
Output:
[1, 2, 13, 3, 4, 5]



RE: how to refer to a subset of a list - Skaperen - Jan-15-2022

what i need is a way to use a function that will store into index 0 (that part cannot be changed) by giving it a subset reference. so if i want it to store into index 47 i would create a subset that starts at 47, such that accessing the subset at 0 accesses the original list at 47. subset[1] would be original[48]. this is done in pointer oriented languages by adding to the pointer. i don't know if it could be done in Python since i don't know the details of how it stores a list in memory. but there are ways to do it.


RE: how to refer to a subset of a list - deanhystad - Jan-16-2022

He wants a C pointer like thing.
int x[10];
int *y = &x[2];



RE: how to refer to a subset of a list - Skaperen - Jan-16-2022

yes.

but i can envision a way to do it in an implementation of a list like object that contains values or references to other objects, with an interface API to this which can be done with methods.
    fake_list = real_list.subset(47,99)
    assert fake_list[0:52] == real_list[47:99]
i simply don't know if any implementation ever did this, like Python or Pike. i don't even want to look at Peril.