I try to access an array dynamically in a loop like array[n-i:-i]
and it works fine as long as i != 0
. In case i==0
I have array[n:0]
, which I would expect to output array
from n to the end but it returns nothing (None
i guess).
How to archive the expected behaviour?
Use None
to slice to the end; Python then'll use len(array)
as the endpoint. Use or
to fall back to None
when -i
is 0
:
array[n-i:-i or None]
Numeric 0 is considered false in Python boolean contexts. The or
operator short-circuits; it returns the first operand if it is a true value, otherwise it'll evaluate the second operand and return that.
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