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 program to convert Set into Tuple and Tuple into Set
Next article icon

Python program to get all subsets of given size of a Set

Last Updated : 21 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a set, and our task is to get all subsets of a given size. For example, if we have s = {1, 2, 3, 4} and need to find subsets of size k = 2, the output should be [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)].

Using itertools.combinations

We can use itertools.combinations(iterable, r) to generate all possible subsets (combinations) of size “r” from the given set without repetition. It returns an iterator of tuples where each tuple represents a unique subset.

Python
from itertools import combinations s = {1, 2, 3, 4} k = 2  # Get all subsets of size k subsets = list(combinations(s, k)) print("Subsets of size", k, ":", subsets) 

Output
Subsets of size 2 : [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] 

Explanation:

  • Combinations(s, k) function generates all possible 2-element subsets from the set {1, 2, 3, 4}, returning an iterator of tuples.
  • List(combinations(s, k)) converts the iterator to a list and the result is printed, displaying all subsets of size 2.

Using bit manipulation

Using bit manipulation we can represent each subset of a set as a binary number where each bit indicates whether an element is included. By iterating through all binary numbers of length equal to set’s size we can filter subsets of the desired size.

Python
s = {1, 2, 3, 4} k = 2  s = sorted(s)  # Ensure consistent ordering n = len(s) res = []  for i in range(1 << n):  # Iterate through all possible combinations     subset = [s[j] for j in range(n) if (i & (1 << j))]     if len(subset) == k:         res.append(subset)  print("Subsets of size", k, ":", res) 

Output
Subsets of size 2 : [[1, 2], [1, 3], [2, 3], [1, 4], [2, 4], [3, 4]] 

Explanation:

  • We iterate through all possible binary numbers of length equal to the size of the set (1 << n gives 2^n possibilities), each bit in the binary representation of i determines whether the corresponding element is included.
  • The expression (i & (1 << j)) checks if the j-th bit is set, meaning the element should be part of the subset.
  • We collect subsets of size k and append them to the result list and Sorting s ensures a consistent lexicographic order of subsets.

Using list comprehensions

List comprehensions can be used to efficiently filter and collect subsets of a given size by iterating over all possible combinations. They offer a concise readable way to generate subsets without explicitly using loops or conditionals.

Python
s = {1, 2, 3, 4} k = 2  s = list(s) n = len(s) res = [[]]  # Iteratively build subsets for ele in s:     ns = [s + [ele] for s in res]     res.extend(ns)  # Filter subsets of size `k` sub = [s for s in res if len(s) == k]  print("Subsets of size", k, ":", sub) 

Output
Subsets of size 2 : [[1, 2], [1, 3], [2, 3], [1, 4], [2, 4], [3, 4]] 

Explanation:

  • Loop iterates over each element creating new subsets by appending element to all existing subsets (s + [ele]), effectively generating all possible subsets.
  • list comprehension [s for s in res if len(s) == k] is used to filter and collect only those subsets with size k


Next Article
Python program to convert Set into Tuple and Tuple into Set

S

Smitha Dinesh Semwal
Improve
Article Tags :
  • Combinatorial
  • DSA
  • Python
  • Python Programs
  • Python set-programs
  • python-set
Practice Tags :
  • Combinatorial
  • python
  • python-set

Similar Reads

  • Python program to get all subsets having sum x
    We are given a list of n numbers and a number x, the task is to write a python program to find out all possible subsets of the list such that their sum is x. Examples: Input: arr = [2, 4, 5, 9], x = 15 Output: [2, 4, 9] 15 can be obtained by adding 2, 4 and 9 from the given list. Input : arr = [10,
    3 min read
  • Python Program to Find Duplicate sets in list of sets
    Given a list of sets, the task is to write a Python program to find duplicate sets. Input : test_list = [{4, 5, 6, 1}, {6, 4, 1, 5}, {1, 3, 4, 3}, {1, 4, 3}, {7, 8, 9}]Output : [frozenset({1, 4, 5, 6}), frozenset({1, 3, 4})]Explanation : {1, 4, 5, 6} is similar to {6, 4, 1, 5} hence part of result.
    8 min read
  • Python program to convert Set into Tuple and Tuple into Set
    Let's see how to convert the set into tuple and tuple into the set. For performing the task we are use some methods like tuple(), set(), type(). tuple(): tuple method is used to convert into a tuple. This method accepts other type values as an argument and returns a tuple type value.set(): set metho
    7 min read
  • How To Create A Set Of Sets In Python?
    Sets are flexible data structures in Python that hold distinct items. There are situations in which you may need to construct a set of sets, even though sets are unordered and flexible in and of themselves. In this article, we will see how to create a set of sets. Note: We can't create a set of sets
    2 min read
  • Python Program for Minimum product subset of an array
    Given an array a, we have to find the minimum product possible with the subset of elements present in the array. The minimum product can be a single element also. Examples:  Input : a[] = { -1, -1, -2, 4, 3 } Output : -24 Explanation : Minimum product will be ( -2 * -1 * -1 * 4 * 3 ) = -24 Input : a
    3 min read
  • Python Program to get K length groups with given summation
    Given a list, our task is to write a Python program to extract all K length sublists with lead to given summation. Input : test_list = [6, 3, 12, 7, 4, 11], N = 21, K = 4 Output : [(6, 6, 6, 3), (6, 6, 3, 6), (6, 3, 6, 6), (6, 7, 4, 4), (6, 4, 7, 4), (6, 4, 4, 7), (3, 6, 6, 6), (3, 3, 3, 12), (3, 3,
    6 min read
  • Get a Subset of Dict in Python
    In Python, dictionaries store key-value pairs and are pivotal in data management. Extracting dictionary subsets based on specific criteria is key for targeted data analysis, ensuring operational efficiency by focusing on relevant data. This technique, vital in data processing and machine learning, a
    3 min read
  • Python Program to Find Most common elements set
    Given a List of sets, the task is to write a Python program tocompare elements with argument set, and return one with maximum matching elements. Examples: Input : test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}], arg_set = {9, 6, 5, 3}Output : {9, 3, 5, 7}Explanation : Resultant
    5 min read
  • Python program to fetch the indices of true values in a Boolean list
    Given a list of only boolean values, write a Python program to fetch all the indices with True values from given list. Let's see certain ways to do this task. Method #1: Using itertools [Pythonic way] itertools.compress() function checks for all the elements in list and returns the list of indices w
    5 min read
  • Find the size of a Set in Python
    A Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements. Python’s set class represents the mathematical notion of a set. The size of a set means the amount of memory (in bytes) occupied by a set object. In this article, we will learn various ways to get th
    2 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