Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - All possible concatenations in String List
Next article icon

Python | All possible N combination tuples

Last Updated : 06 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Time Complexity: O(n!) where n is the number of elements in the list “test_list”. list comprehension + product()  performs n! number of operations.
Auxiliary Space: O(n!), extra space is required where n is the number of elements in the list

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

 Method #3 : Using tuple()

Approach

Use a recursive function to generate all possible combinations of tuples of length N. Start with an empty tuple and iterate through the elements from 1 to N. For each element, call the recursive function with the current tuple concatenated with the element.

Algorithm

1. Define a recursive function to generate all possible combinations of tuples.
2. The function takes two arguments – the current tuple and the current index.
3. If the current index is equal to N, append the current tuple to the result list and return.
4. Otherwise, iterate through the elements from 1 to N. For each element, call the recursive function with the current tuple concatenated with the element and the current index incremented by 1.
5. Initialize an empty result list and call the recursive function with an empty tuple and index 0.
6. Return the result list.

Python3




def tuple_combinations(N):
    def helper(current_tuple, index):
        if index == N:
            result.append(current_tuple)
            return
        for i in range(1, N+1):
            helper(current_tuple + (i,), index+1)
     
    result = []
    helper(tuple(), 0)
    return result
N=3
print(tuple_combinations(N))
 
 
Output
[(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)]

Time Complexity: O(N^N), the recursive function is called N times for each level of recursion, and there are N levels of recursion. In each call, a new tuple is created by concatenating the current tuple with an element, which takes O(N) time.
Space Complexity: O(N^N), the recursive function creates a new tuple on each call, and there are N levels of recursion. Therefore, the total number of tuples created is N^N. Additionally, the result list stores all the tuples, so its size is also N^N. The maximum size of the call stack is also N, since there are N levels of recursion.



Next Article
Python - All possible concatenations in String List
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - All pair combinations of 2 tuples
    Sometimes, while working with Python tuples data, we can have a problem in which we need to extract all possible combination of 2 argument tuples. This kind of application can come in Data Science or gaming domains. Let's discuss certain ways in which this task can be performed. Input : test_tuple1
    6 min read
  • Python - All Possible unique K size combinations till N
    Sometimes, while working with Python domain, we can have a problem in which we need to produce various combination of elements. This can be K sized unique combinations till N. This problem can have application in data domains and school programming. Let's discuss certain ways in which this task can
    4 min read
  • Python List and Tuple Combination Programs
    Lists and tuples are two of the most commonly used data structures in Python. While lists are mutable and allow modifications, tuples are immutable and provide a stable structure for storing data. This article explores various programs related to list and tuple combinations, covering topics like: So
    6 min read
  • Python - All possible items combination dictionary
    Sometimes, while working with data, we can have a problem in which we are provided with sample data of key and value list and we require to construct actual data as all possible combination of keys and value list of similar size. Lets discuss certain ways in which this task can be performed. Method
    4 min read
  • Python - All possible concatenations in String List
    Sometimes, while working with String lists, we can have a problem in which we need to perform all possible concatenations of all the strings that occur in list. This kind of problem can occur in domains such as day-day programming and school programming. Let's discuss a way in which this task can be
    3 min read
  • Python - Split list into all possible tuple pairs
    Given a list, the task is to write a python program that can split it into all possible tuple pairs combinations. Input : test_list = [4, 7, 5, 1, 9] Output : [[4, 7, 5, 1, 9], [4, 7, 5, (1, 9)], [4, 7, (5, 1), 9], [4, 7, (5, 9), 1], [4, (7, 5), 1, 9], [4, (7, 5), (1, 9)], [4, (7, 1), 5, 9], [4, (7,
    3 min read
  • Print all Possible Combinations from the Three Digits - Python
    The task of printing all possible combinations from three digits in Python involves generating all unique ways to arrange the digits, considering their order. For example, given the digits 1, 2, and 3, the goal is to produce all permutations such as [1, 2, 3], [1, 3, 2], [2, 1, 3], and so on. Using
    3 min read
  • Python - Pairwise Addition in Tuples
    Sometimes, while working with data, we can have a problem in which we need to find cumulative result. This can be of any type, product or summation. Here we are gonna discuss about adjacent element addition. Let’s discuss certain ways in which this task can be performed. Method #1 : Using zip() + ge
    4 min read
  • Addition in Nested Tuples - Python
    Sometimes, while working with records, we can have a problem in which we require to perform index wise addition of tuple elements. This can get complicated with tuple elements to be tuple and inner elements again be tuple. Let's discuss certain ways in which this problem can be solved. Method #1: Us
    6 min read
  • Python | Addition of tuples
    Sometimes, while working with records, we might have a common problem of adding contents of one tuple with the corresponding index of other tuple. This has application in almost all the domains in which we work with tuple records. Let's discuss certain ways in which this task can be performed. Metho
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences