Python program to get all subsets of given size of a set
Given a set, write a Python program to generate all possible subset of size n of given set within a list.
Examples:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Input : {1, 2, 3}, n = 2
Output : [{1, 2}, {1, 3}, {2, 3}]
Input : {1, 2, 3, 4}, n = 3
Output : [{1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}]We have already discussed the same problem using the Naive approach in this article. This article focuses on the Pythonic approaches to Print all subsets of a given size of a set.
Python has itertools.combinations(iterable, n) which Return n length subsequences of elements from the input iterable. This can be used to Print all subsets of a given size of a set. Now, we have various alternatives to use this function.
Code #1 :
Simply pass the set as iterable and the size as arguments in the itertools.combinations() to directly fetch the combination list.
Python3
# Python Program to Print# all subsets of given size of a setimport itertoolsdef findsubsets(s, n): return list(itertools.combinations(s, n))# Driver Codes = {1, 2, 3}n = 2print(findsubsets(s, n)) |
[(1, 2), (1, 3), (2, 3)]
Code #2 :
We can also use an alternative to the above-discussed method which is mapping set to itertools.combinations() function.
Python3
# Python Program to Print# all subsets of given size of a setimport itertoolsfrom itertools import combinations, chaindef findsubsets(s, n): return list(map(set, itertools.combinations(s, n))) # Driver Codes = {1, 2, 3}n = 2print(findsubsets(s, n)) |
[{1, 2}, {1, 3}, {2, 3}]
Code #3 :
Another method is to use for loop in itertools.combinations() function and append the combination sets to the list.
Python3
# Python Program to Print# all subsets of given size of a setimport itertools# def findsubsets(s, n):def findsubsets(s, n): return [set(i) for i in itertools.combinations(s, n)] # Driver Codes = {1, 2, 3, 4}n = 3print(findsubsets(s, n)) |
Output:
[{1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}]Code #4:
Many a time when this question is asked in interviews, it’s better to answer without using any module. So, here is the solution that does not use itertools module:
Python3
def subsets(numbers): if numbers == []: return [[]] x = subsets(numbers[1:]) return x + [[numbers[0]] + y for y in x]# wrapper functiondef subsets_of_given_size(numbers, n): return [x for x in subsets(numbers) if len(x)==n]if __name__ == '__main__': numbers = [1, 2, 3, 4] n = 3 print(subsets_of_given_size(numbers, n)) |
Output:
[[2, 3, 4], [1, 3, 4], [1, 2, 4], [1, 2, 3]]


