Python – Extract Similar pairs from List

Sometimes, while working with Python lists, we can have a problem in which we need to perform extraction of all the elements pairs in list. This kind of problem can have application in domains such as web development and day-day programming. Let’s discuss certain ways in which this task can be performed.

Input : test_list = [1, 2, 3, 4]
Output : []

Input : test_list = [2, 2, 2, 2, 3, 3, 4]
Output : [(2, 2), (2, 2), (3, 3)]

Method #1 : Using Counter() + list comprehension
The combination of above functions can be used to solve this problem. In this, frequencies are extracted using Counter() and pairs construction is done used list comprehension.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Extract Similar pairs from List
# Using Counter() + list comprehension
from collections import Counter
  
# initializing list
test_list = [4, 6, 7, 4, 2, 6, 2, 8]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Extract Similar pairs from List
# Using Counter() + list comprehension
res = [(key, key) for key, val in Counter(test_list).items() 
                                  for _ in range(val // 2)]
  
# printing result 
print("The records after pairing : " + str(res)) 

chevron_right


Output :



The original list is : [4, 6, 7, 4, 2, 6, 2, 8]
The records after pairing : [(4, 4), (6, 6), (2, 2)]

 

Method #2 : Using fromkeys() + list comprehension
This is yet another way in which this task can be performed. In this, we perform the task of Counter() using fromkeys() and get() of dictionary, i.e getting frequencies.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Extract Similar pairs from List
# Using fromkeys() + list comprehension
  
# initializing list
test_list = [4, 6, 7, 4, 2, 6, 2, 8]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Extract Similar pairs from List
# Using fromkeys() + list comprehension
temp = dict.fromkeys(test_list, 0)
for key in test_list:
    temp[key] += 1
res = [(key, key) for key, val in temp.items() for _ in range(val // 2)]
  
# printing result 
print("The records after pairing : " + str(res)) 

chevron_right


Output :

The original list is : [4, 6, 7, 4, 2, 6, 2, 8]
The records after pairing : [(4, 4), (6, 6), (2, 2)]



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.