Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a slice using a tuple

Tags:

python

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.

like image 248
Mike Avatar asked Aug 15 '11 21:08

Mike


People also ask

How can you slice a tuple?

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.

Can Slicing be done on tuple?

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.

How do you cut a list of tuples in Python?

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.

Can tuples be indexed and sliced?

Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.


2 Answers

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.

like image 184
Chinmay Kanchi Avatar answered Oct 05 '22 17:10

Chinmay Kanchi


How about a[slice(*b)]?

Is that sufficiently pythonic?

like image 42
Foon Avatar answered Oct 05 '22 18:10

Foon