Open In App

Combinations of Elements till size N in List - Python

Last Updated : 12 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a list and our task is to generate all possible combinations of its elements up to a given size N, including all lengths from 1 to N. For example, if we have a = [1, 2, 3] and N = 2 then the output should be [(1,), (2,), (3,), (1, 2), (1, 3), (2, 3)], where we generate all subsets of size 1 and 2 from the list.

Using combinations() from itertools

itertools.combinations() generates all possible combinations of a given length and we use it in a loop to get combinations from size 1 to N.

Python
from itertools import combinations  

a = [1, 2, 3]  
N = 2  

res = [comb for i in range(1, N + 1) for comb in combinations(a, i)]  

print(res)

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

Explanation:

  • combinations(a, i) generates all combinations of length i.
  • we loop over values from 1 to N and collect all combinations in a list.

Using chain.from_iterable() and combinations()

We can use itertools.chain.from_iterable() to flatten multiple calls to combinations() into a single iterable.

Python
from itertools import chain, combinations  

a = [1, 2, 3]  
N = 2  

res = list(chain.from_iterable(combinations(a, i) for i in range(1, N + 1)))  

print(res)

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

Explanation:

  • combinations(a, i) generates combinations for each length i.
  • chain.from_iterable() merges all these combinations into a single list.

Using Recursion

We can use recursion to generate all possible combinations of elements from size 1 to N.

Python
def generate_combinations(a, n, start=0, curr=[]):
    if 0 < len(curr) <= n:
        res.append(tuple(curr))
    
    for i in range(start, len(a)):
        generate_combinations(a, n, i + 1, curr + [a[i]])

a = [1, 2, 3]
N = 2
res = []

generate_combinations(a, N)
print(res)

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

Explanation:

  • We use recursion to explore all subsets.
  • If the current subset length is between 1 and N then we add it to the result.
  • The loop iterates over the list, adding elements one by one while maintaining order.

Using List Comprehension and Slicing

We can generate combinations manually by iterating through the list using list comprehension and forming subsets of size 1 to N using slicing.

Python
a = [1, 2, 3]  
N = 2  

res = [tuple(a[i:j]) for i in range(len(a)) for j in range(i + 1, min(i + N + 1, len(a) + 1))]  

print(res)

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

Explanation:

  • Outer loop (i) iterates over each starting index of the list.
  • Inner loop (j) iterates from i + 1 to min(i + N + 1, len(a) + 1), ensuring subset size ≤ N.
  • Tuple conversion slices a[i:j] to form a subset and converts it into a tuple.
  • List comprehension is used to collect all valid subsets into res.

Practice Tags :

Similar Reads