Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Tuple Indexing, Combine Slice and Index

i have got a question about tuple indexing and slicing in python. I want to write better and clearer code. This is a simplified version of my problem:
I have a tuple a = (1,2,3,4,5) and i want to index into it so that i get b = (1,2,4).
Is it possible to do this in one operation or do i have do b = a[0:2] + (a[3],)? I have thought about indexing with another tuple, which is not possible, i have also searched if there is a way to combine a slice and an index. It just seems to me, that there must be a better way to do it.

Thank you very much 🙂

Edit:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Solution to the Problem (Mechanic Pig and user_na):

b = operator.itemgetter(*range(2), 3)(a)

>Solution :

As stated in the comment you can use itemgetter

import operator
a = (1,2,3,4)
result = operator.itemgetter(0, 1, 3)(a)

If you do this kind of indexing often and your arrays are big, you might also have a look at numpy as it supports more complex indexing schemes:

import numpy as np
a = (1,2,3,4)
b = np.array(a)
result = b[[0,1,3]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading