
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python program to get all subsets of a given size of a set
In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given a set, we need to list all the subsets of size n
We have three approaches to solve the problem −
Using itertools.combinations() method
Example
# itertools module import itertools def findsubsets(s, n): return list(itertools.combinations(s, n)) #main s = {1,2,3,4,5} n = 4 print(findsubsets(s, n))
Output
[(1, 2, 3, 4), (1, 2, 3, 5), (1, 2, 4, 5), (1, 3, 4, 5), (2, 3, 4, 5)]
Using map() and combination() method
Example
# itertools module from itertools import combinations def findsubsets(s, n): return list(map(set, itertools.combinations(s, n))) # Driver Code s = {1, 2, 3, 4, 5} n = 4 print(findsubsets(s, n))
Output
[{1, 2, 3, 4}, {1, 2, 3, 5}, {1, 2, 4, 5}, {1, 3, 4, 5}, {2, 3, 4, 5}]
Using comprehension in the list iterable
Example
# itertools import itertools def findsubsets(s, n): return [set(i) for i in itertools.combinations(s, n)] # Driver Code s = {1, 2, 3, 4, 5} n = 4 print(findsubsets(s, n))
Output
[{1, 2, 3, 4}, {1, 2, 3, 5}, {1, 2, 4, 5}, {1, 3, 4, 5}, {2, 3, 4, 5}]
Conclusion
In this article, we have learned about how we can get all subsets of a given size of a set
- Related Articles
- Python program to get all subsets of given size of a set
- Print all subsets of given size of a set in C++
- Python Program to Create a Class and Get All Possible Subsets from a Set of Distinct Integers
- Find all distinct subsets of a given set in C++
- C++ Program to Generate All Subsets of a Given Set in the Lexico Graphic Order
- Python program to get all permutations of size r of a string
- Python program to get all subsets having sum s\n
- How to find all subsets of a set in JavaScript?
- List all the subsets of a set {m , n}
- Golang program to find all subsets of a string
- Swift program to Get the Size of Set
- Java Program To Find all the Subsets of a String
- C++ Program to Generate All Pairs of Subsets Whose Union Make the Set
- Count number of subsets of a set with GCD equal to a given number in C++
- Sum of all subsets of a set formed by first n natural numbers

Advertisements