Warm tip: This article is reproduced from stackoverflow.com, please click
indexing list python range slice

Is there a smarter way for getting the indices of a list sliced with a sliced object?

发布于 2020-03-31 23:00:48

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)

Questioner
jonka
Viewed
67
Masklinn 2020-01-31 22:52
indices_B = range(*my_slice.indices(len(my_list_A)))

https://docs.python.org/3/reference/datamodel.html#slice.indices