Python - Finding tuples within a tuple

  • A tuple is a collection of immutable items separated by commas, placed within (). Tuples can hold any object types or can also hold other tuples within. In this sample we will see, how to check if a tuple contains a particular item.

    For a single dimensional tuple, to check if a value exists in a tuple, most of the websites suggests using any as in sample below. But this may not give us the desired results in most of the cases.
    In the sample below, a search for value Ear also returns a True. This could be wrong if we are looking for an exact match.

    tup = ("Mercury", "Venus", "Earth", "Mars")
     
    if (any('Mercury' in i for i in tup)) :
        print("Planet present")
    
    #This could be wrong if we want an exact match
    if (any('Ear' in i for i in tup)) :
        print("Planet present")
    
  • Additionally, for 2D tuple, using any will give you unexpected results.
    Below we have a group of holidays (a combination of month and day) as tuple, from which we want to check for an exact match.
    Using any will return True, if the searched value is present anywhere. This is not the expected result.

    holidays = ( (1, 20), (1, 25), (1, 15), (3, 1) )
    
    if (any(25 in i for i in holidays)) :
        print("Present")
    
  • Easiest way to check if a tuple exists in another tuple is to use a function as below.

    Copied
    holidays = ( (1, 20), (1, 25), (2, 15), (3, 1) )
    
    def checkTupleExist(tup):
        for m, d in holidays:
            if(m == tup[0] and d == tup[1]):
                return True
        return False
    
    print(checkTupleExist( (1, 20) ))
    

    Output will be true only for an exact match.

Absolute Code Works - Python Topics