17

I am trying to figure out how to determine if a tuple has an exact match in a list of tuples, and if so, return the index of the matching tuple. For instance if I have:

TupList = [('ABC D','235'),('EFG H','462')]

I would like to be able to take any tuple ('XXXX','YYYY') and see if it has an exact match in TupList and if so, what its index is. So for example, if the tuple ('XXXX','YYYY') = (u'EFG H',u'462') exactly, then the code will return 1.

I also don't want to allow tuples like ('EFG', '462') (basically any substring of either tuple element) to match.

Obito
  • 391
  • 3
  • 8
Mark Clements
  • 465
  • 7
  • 25

2 Answers2

17

Use list.index:

>>> TupList = [('ABC D','235'),('EFG H','462')]
>>> TupList.index((u'EFG H',u'462'))
1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • 1
    Small note- if the tuple doesn't exist in the list this will spit out an error. – yuvi Nov 27 '13 at 10:08
  • Thank you so much @hcwhsa. This is what I needed, however, I also need my code to not break due to an error generated if the particular tuple I'm looking for is not in the list. Is there any easy way to get around this aside from doing it in two steps using `if ((u'EFG H', u'462')) in TupList == False:` and then continuing on or `else: TupList.index((u'EFG H',u'462'))`? – Mark Clements Nov 27 '13 at 23:45
  • Thanks @Ashwini Chaudhary this is very helpful. What if you have repeating elements? ```TupList = [('ABC D','235'),('EFG H','462'), ('EFG H','462')]``` .index seems to only give me 1 value – Yi Xiang Chong Jul 10 '20 at 09:58
  • @YiXiangChong You will have to use a loop in that case: `[index for index, item in enumerate(TupList) if item == (u'EFG H',u'462')]` – Ashwini Chaudhary Jul 10 '20 at 10:51
3

I think you can do it by this

TupList = [('ABC D','235'),('EFG H','462')]
if ('ABC D','235') in TupList:
   print TupList.index(i)
Mero
  • 1,280
  • 4
  • 15
  • 25