Home > Net >  Slicing certain elements of a tuple
Slicing certain elements of a tuple

Time:11-03

If I have tuple:

myT=(“a”, “b”, “c”, “d”, “e”, “f”)

Is it possible to slice out say “a”, “d”, “e”?

Something like myT = myT[0, 3, 4].

CodePudding user response:

I don't think there is a standard concise way to write something like that.

What you can do is:

a = ('a', 'b', 'c', 'd', 'e', 'f')
b = (a[0], a[3], a[4])

Or, if you don't want to refer to a more than once, the simplest option should be something like this:

b = tuple(a[x] for x in [0, 3, 4])

But if you find that you need this in multiple places, you can consider writing a utility function.

CodePudding user response:

operator.itemgetter could be worth a try. At least it looks quite similar to what you're asking for:

from operator import itemgetter

myT = tuple("abcdef")

# ('a', 'd', 'e')
print(itemgetter(0,3,4)(myT))
  • Related