Create A Slice Using A Tuple
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 >>&
Solution 1:
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.
Solution 2:
How about a[slice(*b)]
?
Is that sufficiently pythonic?
Solution 3:
slice
takes up to three arguments, but you are only giving it one with a tuple. What you need to do is have python unpack it, like so:
a[slice(*b)]
Solution 4:
Only one tiny character is missing ;)
In [2]: a = range(20)
In [3]: b = (5, 12)
In [4]: a[slice(*b)]
Out[4]: [5, 6, 7, 8, 9, 10, 11
Post a Comment for "Create A Slice Using A Tuple"