Q:

Python program to perform comparison operation on tuples

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Performing comparison operation on tuples

In this program, we are given two tuples. We need to create a Python program to return a tuple that contains the comparison elements. The program will return True or False based on whether values of tuple1 are greater than that of tuple2.

Input:
tuple1 = (5, 8, 9) , tuple2 = (3, 7, 8)

Output:
True

We will be comparing each element of the tuples and return a boolean value if the value at a given index is greater.

  • True: If values at all index in tuple1 are greater than corresponding elements of tuple2.
  • False: All other cases.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to solve the problem is by comparing elements at a given index using generator expression and zip() method. And use all() methods to check for all values to be truthy.

# Python program to perform comparison 
# operation on Tuples

# Initializing and printing the tuples 
tup1 = (5, 8, 9)
tup2 = (3, 7, 8)
print("The elements of tuple 1 are " + str(tup1))
print("The elements of tuple 2 are " + str(tup2))

# Comparing tuple values
isTup1Great = all(x > y for x, y in zip(tup1, tup2))

if isTup1Great : 
    print("All elements of first tuple are greater that tuple second ")
else :
    print("All elements of first tuple are not greater than tuple second ")

Output:

The elements of tuple 1 are (5, 8, 9)
The elements of tuple 2 are (3, 7, 8)
All elements of first tuple are greater that tuple second

Method 2:

Another method to solve the problem is by using a map() method with a lambda function that compares elements of the tuple. And use all() methods to check if all elements are greater.

# Python program to perform comparison 
# operation on Tuples

# Initializing and printing the tuples 
tup1 = (5, 8, 9)
tup2 = (3, 7, 8) 
print("The elements of tuple 1 are " + str(tup1))
print("The elements of tuple 2 are " + str(tup2))

# Comparing tuple values
isTup1Great = all(map(lambda x, y: x < y, tup1, tup2))

if isTup1Great : 
    print("All elements of first tuple are greater that tuple second ")
else :
    print("All elements of first tuple are not greater than tuple second ")

Output:

The elements of tuple 1 are (5, 8, 9)
The elements of tuple 2 are (3, 7, 8)
All elements of first tuple are not greater than tuple second

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to check if the tuple has any none ... >>
<< Python program to perform multiplication operation...