Skip to content
Related Articles
Open in App
Not now

Related Articles

Python – Extract Similar pairs from List

Improve Article
Save Article
Like Article
  • Last Updated : 13 Mar, 2023
Improve Article
Save Article
Like Article

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. 

Python3




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

Time Complexity: O(n*n) where n is the number of elements in the in the list “test_list”. The Counter() + list comprehension is used to perform the task and it takes O(n*n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the in the list “test_list”.

  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




# 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
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!