How do you find all pairs in python?

Sometimes, while working with Python list, we can have a problem in which we need to extract all the possible pairs that can be performed from integers from list. This kind of problem can occur in many domains such as day-day programming and web development. Let’s discuss certain ways in which this task can be performed.

Input : test_list = [1, 7, 4]
Output : [(1, 7), (1, 4), (7, 4)]

Input : test_list = [7, 4]
Output : [(7, 4)]

Method #1 : Using list comprehension + enumerate()
This is one of the ways in which this task can be performed. In this, we perform the task of pairing using nested loops in list comprehension recipe, and enumerate() is used to check with the next indices while iteration.

test_list = [1, 7, 4, 3]

print("The original list : " + str(test_list))

res = [(a, b) for idx, a in enumerate(test_list) for b in test_list[idx + 1:]]

print("All possible pairs : " + str(res))

Output :

The original list : [1, 7, 4, 3]
All possible pairs : [(1, 7), (1, 4), (1, 3), (7, 4), (7, 3), (4, 3)]

Method #2 : Using combinations()
This is one of the ways in which this task can be performed. In this, we just using inbuild function for pairing and sending 2 as value for making pairs of size 2.

from itertools import combinations

test_list = [1, 7, 4, 3]

print("The original list : " + str(test_list))

res = list(combinations(test_list, 2))

print("All possible pairs : " + str(res))

Output :

The original list : [1, 7, 4, 3]
All possible pairs : [(1, 7), (1, 4), (1, 3), (7, 4), (7, 3), (4, 3)]


Given a list. The task is to write a Python program to get all pairwise combinations from the list.

Finding all Pairs (No uniqueness)

Example:

Input: [1,”Mallika”,2,”Yash”]

Output: [(1, ‘Mallika’), (1, 2), (1, ‘Yash’), (‘Mallika’, 1), (‘Mallika’, 2), (‘Mallika’, ‘Yash’), (2, 1), (2, ‘Mallika’), (2, ‘Yash’), (‘Yash’, 1), (‘Yash’, ‘Mallika’), (‘Yash’, 2)]

Method 1: Using simple loops

We can access all combinations of the list using two loops to iterate over list indexes. If both the index counters are on the same index value, we skip it, else we print the element at index i followed by the element at index j in order. 

The time complexity of this method is O(n2) since we require two loops to iterate over lists. 

Python3

lst = [1,"Mallika",2,"Yash"]

output = []

for i in range(0,len(lst)):

    for j in range(0,len(lst)):

        if (i!=j):

            output.append((lst[i],lst[j]))

print(output)

Output:

[(1, ‘Mallika’), (1, 2), (1, ‘Yash’), (‘Mallika’, 1), (‘Mallika’, 2), (‘Mallika’, ‘Yash’), (2, 1), (2, ‘Mallika’), (2, ‘Yash’), (‘Yash’, 1), (‘Yash’, ‘Mallika’), (‘Yash’, 2)]

Method 2: Using itertools

Python provides support of itertools standard library which is used to create iterators for efficient looping. The library provides support for various kinds of iterations, in groups, sorted order, etc. The permutations() functions of this library are used to get through all possible orderings of the list of elements, without any repetitions. The permutations() functions have the following syntax:

itertools.permutations(lst,r)

Where r depicts the r-length tuples, that is, 2 depicts a pair,3 depicts a triplet. The first argument is the specified list.  

The function returns the list of groups of elements returned after forming the permutations. The output contains n x (n-1) number of elements, where n is the size of the list since each element is subsequently is multiplied with all others. The time required to compute permutations is roughly exponential in the order of the size of the list. 

Python3

import itertools

lst = [1, "Mallika", 2, "Yash"]

pair_order_list = itertools.permutations(lst, 2)

print(list(pair_order_list))

Output:

[(1, ‘Mallika’), (1, 2), (1, ‘Yash’), (‘Mallika’, 1), (‘Mallika’, 2), (‘Mallika’, ‘Yash’), (2, 1), (2, ‘Mallika’), (2, ‘Yash’), (‘Yash’, 1), (‘Yash’, ‘Mallika’), (‘Yash’, 2)]

Note: 

  • The pairs are printed in the order of the sequence of arrival of elements in the list.
  • In the case of all same elements, the method still continues to form pairs and return them, even if they are duplicates.

Python3

import itertools

lst = [2,2,2]

ordered_list = itertools.permutations(lst,2)

for i in ordered_list:

    print(i)

Output :

(2, 2)
(2, 2)
(2, 2)
(2, 2)
(2, 2)
(2, 2)

Finding all Unique Pairs (Uniqueness)

However, the permutations’ method doesn’t distinguish between (a, b) and (b, a) pairs and returns them both. The itertools library also supports a combinations() method that prints either of the (a, b) or (b, a) pairs and not both. The output number of elements is equivalent to (n-1)! where n is the length of the list. The time required to compute combinations is roughly polynomial. 

Example:

Input: [1,”Mallika”,2,”Yash”]

Output: [(1, ‘Mallika’), (1, 2), (1, ‘Yash’), (‘Mallika’, 2), (‘Mallika’, ‘Yash’), (2, ‘Yash’)]

Python3

import itertools

3 to integers and strings

lst = [1,"Mallika",2,"Yash"]

pair_order_list = itertools.combinations(lst,2)

print (list(pair_order_list))

Output:

[(1, ‘Mallika’), (1, 2), (1, ‘Yash’), (‘Mallika’, 2), (‘Mallika’, ‘Yash’), (2, ‘Yash’)]


How do you find a pair in Python?

First, we take an empty list 'res' and start a loop and traverse each element of the given list of integers. In each iteration, pop the element, store it in 'num', find remaining difference for sum K, and check if the difference exists in the given list or not.

How do you find the pair of elements in a list in Python?

Pair iteration in a list using zip() + list slicing. The zip function can be used to extract pairs over the list slicing can be used to successively pair the current element with the next one for efficient pairing.

How do you find all possible pairs in an array?

In order to find all the possible pairs from the array, we need to traverse the array and select the first element of the pair. Then we need to pair this element with all the elements in the array from index 0 to N-1. Below is the step by step approach: Traverse the array and select an element in each traversal.

What is pair () in Python?

Pairing functions take two integers and give you one integer in return. What makes a pairing function special is that it is invertable; You can reliably depair the same integer value back into it's two original values in the original order.