I have a list A of unknown length and a slice object that indicates important elements in this list. How can I get the according indices as a list B? (So Instead of e.g. slice(0, 5, 1)
I get [0, 1, 2, 3, 4]
) This should work even if I don't know the length of the list before defining the slice object and also for slices like s=slice(None, None, 20)
.
My solution is the following:
indices_B = list(range(len(my_list_A)))[my_slice]
It works, but I have a feeling that there has to be a smarter way that is also easier to understand. (Using range(len(somelist))
feels definitely wrong)
indices_B = range(*my_slice.indices(len(my_list_A)))
https://docs.python.org/3/reference/datamodel.html#slice.indices
I think you have to convert to list each range
Rarely: ranges support most list operations (they're proper sequences) and they're much, much cheaper. If you need to pass that to something which only works with actual lists then yes, but that's a separate concern.
the OP question indicates that the desired output is a list
your code will not work for my_slice=slice(None, None, 20)
"the OP question indicates that the desired output is a list" the OP wants the indices, they never actually say that they need a list