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.

0

2 Answers 2

17

Use list.index:

>>> TupList = [('ABC D','235'),('EFG H','462')] >>> TupList.index((u'EFG H',u'462')) 1 
Sign up to request clarification or add additional context in comments.

4 Comments

Small note- if the tuple doesn't exist in the list this will spit out an error.
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'))?
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
@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')]
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) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.