VOOZH about

URL: https://www.geeksforgeeks.org/python/python-all-possible-pairs-in-list/

⇱ All Possible Pairs in List - Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

All Possible Pairs in List - Python

Last Updated : 15 Jul, 2025

We are given a list and our task is to generate all possible pairs from the list. Each pair consists of two distinct elements from the list. For example: a = [1, 2, 3] then the output will be [(1,2), (1,3), (2,3)].

Using combinations() from itertools

combinations() function from the itertools module generates all possible pairs without repetition efficiently.


Output
[(1, 2), (1, 3), (2, 3)]

Explanation:

  • combinations(a, 2) generates all unique pairs from a.
  • list(...) converts the result into a list of tuples.

Using List Comprehension

List comprehension provides a more concise way to generate all possible pairs.


Output
[(1, 2), (1, 3), (2, 3)]

Explanation: This is a compact version of the nested loop method, the outer loop selects a[i] and the inner loop selects a[j], ensuring i < j.

Using Nested Loops

A simple way to generate all possible pairs is by using two nested loops.


Output
[(1, 2), (1, 3), (2, 3)]

Explanation: The outer loop picks an element a[i] and the inner loop picks elements a[j] (where j > i) to ensure unique pairs.

Using zip() with Slicing

We can use zip() along with slicing to generate pairs although this method is not recommended for general cases.


Output
[(1, 2), (1, 3), (2, 3)]

Explanation:

  • enumerate(a) iterates with index i and value x.
  • a[i + 1:] gives the remaining elements to form pairs.
Comment