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 : []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 comprehensionfrom collections import Counter # initializing listtest_list = [4, 6, 7, 4, 2, 6, 2, 8] # printing original listprint("The original list is : " + str(test_list)) # Extract Similar pairs from List# Using Counter() + list comprehensionres = [(key, key) for key, val in Counter(test_list).items() for _ in range(val // 2)] # printing result print("The records after pairing : " + str(res)) |
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 listtest_list = [4, 6, 7, 4, 2, 6, 2, 8] # printing original listprint("The original list is : " + str(test_list)) # Extract Similar pairs from List# Using fromkeys() + list comprehensiontemp = dict.fromkeys(test_list, 0)for key in test_list: temp[key] += 1res = [(key, key) for key, val in temp.items() for _ in range(val // 2)] # printing result print("The records after pairing : " + str(res)) |
The original list is : [4, 6, 7, 4, 2, 6, 2, 8] The records after pairing : [(4, 4), (6, 6), (2, 2)]


