Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python – Extract Similar pairs from List

  • Last Updated : 02 Jun, 2020

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 : []

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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.




# 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)) 
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.




# 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)) 
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
Recommended Articles
Page :

Start Your Coding Journey Now!