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.
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.
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]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With