Create a slice using a tuple

Question:

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.

Asked By: Mike

||

Answers:

How about a[slice(*b)]?

Is that sufficiently pythonic?

Answered By: Foon

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)]
Answered By: Ethan Furman

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.

Answered By: Chinmay Kanchi

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
Answered By: Martin Thurau
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.