I have been using the a[0:2] format for ranges but it has been bothering me that if I have a = range(0, 5) I get a[0, 1, 2, 3, 4] but if I use a[0:-1] I get a[0, 1, 2, 3].
I know if I use a[0:] I get the full range, but if I want to have the end of the range defined by a variable (example: c = -1 then a[0,c]) there is no way for me to get the full range without using a conditional statement (for instance: if c == -1: c = None).
Is there some nice format that I could use to be able to access the whole range while using variables as the limits? Or am I stuck needing a conditional statement?
Thanks.
Edit: It appears I have two options available, I can either set the variable to None conditionally or I can set the variable so that the last term is set at len(a). I am not 100% sure which way I am going to go with yet, but thank you all for your responses.
Just assign None to c:
c = None
a[2:c]
It works as you want. Actually that's how slices (not ranges) are created.
They are actually ordinary Python objects. You can even use them inside [].
a = [0, 1, 2, 3]
s = slice(2, None)
a[s] # equal to a[2:]
a[0:] is just syntactic sugar for a[0:len(a)]
Thus
c = len(a)
a[0:c] #a[:c], a[:], a[0:] all work as well
Gives you the full range.
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