Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Slice A List by Passing A List or A Tuple Returned By A Function in Python?

I have lambda functions as below:

e_by_p = 20
prange_py = lambda x: (e_by_p*x-e_by_p, e_by_p*x)

So the outputs as below:

prange_py(1)
# (0, 20)
prange_py(2)
# (20,40)
prange_py(3)
# (40, 60)
# goes like that

So I want a list to be sliced with the values this function returns. For instance, assuming I have a list as below:

numbers = list(range(100,200))
# This is a default way to slice
numbers[0:20]
# [100, ..., 119]
# Using my function, passing <x> arg as 1
numbers[prange(1)[0]:prange(1)[1]]

However, this is not what I want to do. This is (i) too ugly, (ii) executing the same function twice. So I wonder if there is a way to pass a function's return which is tuple or list as a slice argument to a list.

like image 260
Eray Erdin Avatar asked Dec 14 '22 08:12

Eray Erdin


2 Answers

You can create a slice object using slice() and pass in the function result as arguments:

numbers[slice(*prange_py(1))]

The * unpacks the tuple that prange_py() returns and passes it as arguments to the slice() call.

like image 141
poke Avatar answered May 02 '23 02:05

poke


Construct a slice object explicitly instead of using the : syntax.

numbers[slice(*prange_py(1))]

The tuple returned by prange_py is unpacked to pass two arguments to slice. slice(a,b) creates an object that can be used as an "index" equivalent to numbers[a:b].

like image 39
chepner Avatar answered May 02 '23 01:05

chepner