Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic list slicing with variable step size?

To frame the question, let's assume I've got the following list in Python, where X is some arbitrarily large natural number:

l = [1, 2, 3, 4, 5, 6, 7, ... X]

And I want to slice it such that I take the first, second, third, fifth, eighth, etc. elements of the list, abiding by the Fibonacci sequence. E.g. an operation akin to:

l_prime = [l[0], l[1], l[2], l[4], l[7], l[11], ...]

I'm comfortable with Python indexing notation, of l[start:end:step_size], and I'm wondering if there's a way to index Python lists within this notational paradigm with a step size that varies after each index is added to my new sliced list. Or, would I need to use some other technique to solve the prior problem I posed?

like image 901
zen_of_python Avatar asked Jul 11 '26 08:07

zen_of_python


2 Answers

If you can use numpy this is really easy.

l = np.array([1, 2, 3, 4, ..., X])
fibs = np.array([0, 1, 2, 4, 7])
print(l[fibs])
like image 149
Priyatham Avatar answered Jul 13 '26 12:07

Priyatham


If you want to retrieve multiple elements from the list you can use the function itemgetter():

from operator import itemgetter

lst = [1, 2, 3, 4, 5, 6, 7, 8]
ind = [0, 0, 1, 2, 4, 7] 

itemgetter(*ind)(lst)
# (1, 1, 2, 3, 5, 8)
like image 36
Mykola Zotko Avatar answered Jul 13 '26 10:07

Mykola Zotko