0

I am learning Python3 and I'm in tuples chapter now.

While we can use index method to print the place of an item like this:

>>> tup = ('a','b','a','c')
>>> tup.index('c')
>>> 3

But when I try to print the index for repeated item, it only prints for the first item and simply ignore the second one.

>>> tup.index('a')
    0

I am expecting tuple to print both index (location).

Expected output

>>> tup.index('a')
    0, 2

May I know why tuple having this behaviour? what if if we want to print the index for the repeated item in the tuple?

smc
  • 2,175
  • 3
  • 17
  • 30
  • 1
    not only **tuple**, any sequence will return the first catch – RomanPerekhrest Oct 02 '19 at 08:36
  • Possible duplicate of [Index of duplicates items in a python list](https://stackoverflow.com/questions/5419204/index-of-duplicates-items-in-a-python-list) – user10455554 Oct 02 '19 at 08:37
  • 2
    Possible duplicate of [How to find all occurrences of an element in a list?](https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list) – Georgy Oct 02 '19 at 08:47

3 Answers3

5

tuple.index is actually a three-argument function: tuple.index(x, start, end). It finds the first element equal to x in the range tuple[start:end]. It's just that by default start = 0 and end = len(t).

If you want the index of the second element you can do:

>>> i = tup.index('a')
>>> tup.index('a', i + 1)
2

If you want all indices you can use a list comprehension like L3viathan suggests.

orlp
  • 112,504
  • 36
  • 218
  • 315
4

Because that's what tuple.index does:

>>> help(tup.index)
index(...)
    T.index(value, [start, [stop]]) -> integer -- return first index of value.
    Raises ValueError if the value is not present.

If you want all indices, you can make a list comprehension:

indices = [i for i, val in enumerate(tup) if val == 'c']
L3viathan
  • 26,748
  • 2
  • 58
  • 81
1

You can also do this with numpy.argwhere

https://docs.scipy.org/doc/numpy/reference/generated/numpy.argwhere.html

import numpy as np

np.argwhere(tup == 'a')
Simon Crane
  • 2,122
  • 2
  • 10
  • 21