Is there any way in python to use a tuple as the indices for a slice? The following is not valid:
>>> a = range(20) >>> b = (5, 12) # my slice indices >>> a[b] # not valid >>> a[slice(b)] # not valid >>> a[b[0]:b[1]] # is an awkward syntax [5, 6, 7, 8, 9, 10, 11] >>> b1, b2 = b >>> a[b1:b2] # looks a bit cleaner [5, 6, 7, 8, 9, 10, 11]
It seems like a reasonably pythonic syntax so I am surprised that I can't do it.
To index or slice a tuple you need to use the [] operator on the tuple. When indexing a tuple, if you provide a positive integer, it fetches that index from the tuple counting from the left. In case of a negative index, it fetches that index from the tuple counting from the right.
We can use slicing in tuples I'm the same way as we use in strings and lists. Tuple slicing is basically used to obtain a range of items. Furthermore, we perform tuple slicing using the slicing operator.
In Python, by using a slice (e.g.: [2:5:2] ), you can extract a subsequence of a sequence object, such as a list, string, tuple, etc.
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
You can use Python's *args
syntax for this:
>>> a = range(20) >>> b = (5, 12) >>> a[slice(*b)] [5, 6, 7, 8, 9, 10, 11]
Basically, you're telling Python to unpack the tuple b
into individual elements and pass each of those elements to the slice()
function as individual arguments.
How about a[slice(*b)]
?
Is that sufficiently pythonic?
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