1

I was wondering if tuple unpacking can be used in a "index from ... to" kind of style, so with inds = (a,b), M[*inds] would lead to M[a:b].

I often have tuples which contain the indices that I use to slice my data into some interesting subset, and would think that something like the proposed above would be convenient. Is there a way to do this?

thanks for input

1
  • You can try to patch/overload the getitem method of your list objects, such thath M[inds] is supported. Commented Feb 11, 2016 at 10:30

2 Answers 2

6

You can use tuple unpacking, but you have to unpack them into a slice, and then use the slice for indexing:

>>> A = list(range(10))
>>> inds = 3, 6
>>> A[slice(*inds)]
[3, 4, 5]

Also works with numpy:

>>> B = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> ind_x, ind_y = (0,2), (1,None)
>>> B[slice(*ind_x),slice(*ind_y)]
array([[2, 3],
       [5, 6]])

Remember that A[start:stop:step] is just syntactic sugar for A[slice(start,stop,step)].

Sign up to request clarification or add additional context in comments.

1 Comment

thank you for reminding me. Still new to this stackoverflow system.
0

You cannot use tuples (at least not in the start-stop-step way). But you can always use slice.

some examples:

indx = slice(start, stop, step)
indy = slice(starty, stopy, stepy)
sliced = M[indx]
sliced2 = M[:,indy]
sliced3 = M[(indx, indy)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.