Q:

Python program to find the maximum element in tuple list

belongs to collection: Python Tuple Programs

0

Example:

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

Finding the maximum element in tuple list

In this article, we are given a list of tuples. We need to create a Python program to find the maximum element in the tuple list.

Input: 
[(4, 1, 6), (2, 3, 9), (12, 7, 5)]

Output:
12

We need to iterate through all the elements of the tuple list and find the maximum value from all of them which is our required value.

All Answers

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

Method 1:

One method to find the maximum element of the tuple list is by iterating over the list of tuples using a generator expression and then finding the maximum value from the resultant collection/iterator using the max() method.

# Python program to find the 
# maximum element in tuple list
  
# Initializing and printing 
# the list of tuples 
tupList = [(4, 1, 6), (2, 3, 9), (12, 7, 5)]
print("The element of list of tuples are " + str(tupList))
  
# Finding Maximum elements 
# in Tuple list 
maxVal = max(int(j) for i in tupList for j in i)
print("The Maximum value from the list of tuples is : " + str(maxVal))

Output:

The element of list of tuples are [(4, 1, 6), (2, 3, 9), (12, 7, 5)]
The Maximum value from the list of tuples is : 12

Method 2:

Another method to solve the problem is by flattening the list of tuples using the from_iterable() method from the chain library. Then, we will find the maximum value from the created the map() using the max() method.

# Python program to find the 
# maximum element in tuple list
  
from itertools import chain   
  
# Initializing and printing 
# the list of tuples 
tupList = [(4, 1, 6), (2, 3, 9), (12, 7, 5)]
print("The element of list of tuples are " + str(tupList))
  
# Finding Maximum elements 
# in Tuple list 
maxVal = max(map(int, chain.from_iterable(tupList)))
print("The Maximum value from the list of tuples is : " + str(maxVal))

Output:

The element of list of tuples are [(4, 1, 6), (2, 3, 9), (12, 7, 5)]
The Maximum value from the list of tuples is : 12

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 add a dictionary to tuple... >>
<< Python program to access front and rear element fr...