Python – Filter unique valued tuples


When it is required to filter unique valued tuples from a list of tuples, the ‘list’ and ‘set’ methods are used.

Example

Below is a demonstration of the same −

my_list = [(42, 51), (46, 71), (14, 25), (26, 91), (56, 0), (11, 1), (99,102)]
print("The list of tuple is :")
print(my_list)
my_list.sort()
print("The list after sorting is :")
print(my_list)
my_result = list(set(my_list))
print("The result is :")
print(my_result)

Output

The list of tuple is :
[(42, 51), (46, 71), (14, 25), (26, 91), (56, 0), (11, 1), (99, 102)]
The list after sorting is :
[(11, 1), (14, 25), (26, 91), (42, 51), (46, 71), (56, 0), (99, 102)]
The result is :
[(11, 1), (26, 91), (42, 51), (46, 71), (56, 0), (14, 25), (99, 102)]

Explanation

  • A list of tuple of integers is defined and is displayed on the console.

  • It is sorted using the ‘sort’ method.

  • This is displayed on the console.

  • It is converted to a set to get the unique values, and then to a list.

  • This result is assigned to a variable.

  • This is the output that is displayed on the console.

Updated on: 13-Sep-2021

178 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements