Skip to content
Related Articles

Related Articles

Python | All possible N combination tuples

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 11 Jan, 2022

Sometimes, while working with Python tuples, we might have a problem in which we need to generate all possible combination pairs till N. This can have application in mathematics domain. Let’s discuss certain ways in which this problem can be solved.

Method #1 : Using list comprehension + product()
This task can be performed using list comprehension which can be used to iterate the container of N numbers and product() performs the task of formation of combinations from them.

Python3




# Python3 code to demonstrate working of
# All possible N combination tuples
# Using list comprehension + product()
from itertools import product
  
# initialize N 
N = 3
  
# All possible N combination tuples
# Using list comprehension + product()
res = [ele for ele in product(range(1, N + 1), repeat = N)]
  
# printing result
print("Tuple Combinations till N are : " + str(res))

Output :

Tuple Combinations till N are : [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 1), (3, 3, 2), (3, 3, 3)]

 

Method #2 : Using product()
This task can also be performed by using just the single function. The use of list comprehension can be eliminated using the conversion to list.

Python3




# Python3 code to demonstrate working of
# All possible N combination tuples
# Using product()
from itertools import product
  
# initialize N 
N = 3
  
# All possible N combination tuples
# Using product()
res = list(product(range(1, N + 1), repeat = N))
  
# printing result
print("Tuple Combinations till N are : " + str(res))

Output :

Tuple Combinations till N are : [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 1), (3, 3, 2), (3, 3, 3)]


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!