Python - Total equal pairs in List


When it is required to find the total equal pairs in a list, the ‘set’ operator and the ‘//’ operator along with an iteration can be used.

Example

Below is a demonstration of the same

my_list = [34, 56, 12, 32, 78, 99, 67, 34, 52, 78, 99, 10, 0, 11, 23,9]
print("The list is :")
print(my_list)

all_elems = set(my_list)
my_result = 0
for elements in all_elems:
   my_result += my_list.count(elements) // 2

print("The total pairs are :")
print(my_result)

Output

The list is :
[34, 56, 12, 32, 78, 99, 67, 34, 52, 78, 99, 10, 0, 11, 23, 9]
The total pairs are :
3

Explanation

  • A list is defined and is displayed on the console.

  • The list is converted into a set and assigned to a variable.

  • An integer is assigned the value of 0.

  • The elements in the set are iterated over, and the ‘//’ operator is used.

  • This is added to the result.

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

Updated on: 15-Sep-2021

499 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements