Python Program To Find all the Subsets of a String

In Python, a subset of a string is a sequence of characters that appears in the original string. We can find all the subsets of a string using the itertools module to generate combinations of characters. In this article, we will see how to generate all possible subsets by creating combinations of different lengths.

Syntax

itertools.combinations(iterable, r)

The combinations() function takes an iterable (like a string) and r which represents the length of combinations to generate. It returns all possible combinations of that specific length.

Algorithm

  • Initialize an empty list to store combinations

  • Use a for loop to generate combinations of all possible lengths (0 to string length)

  • Convert each combination tuple to a string and add to results

  • Return the list of all subsets

Example

In the following example, we import the itertools module and create a function to find all subsets. The function generates combinations for each possible length from 1 to the string length ?

import itertools

def find_subsets(text):
    # Get all possible combinations of characters in the string
    combinations = []
    for i in range(1, len(text) + 1):  # Start from 1 to exclude empty string
        combinations += list(itertools.combinations(text, i))
    
    # Convert combinations to strings
    subsets = []
    for combo in combinations:
        subset = ''.join(combo)
        subsets.append(subset)
    
    return subsets

# Test the function
text = 'abc'
subsets = find_subsets(text)
print("Subsets of '{}':".format(text))
print(subsets)
Subsets of 'abc':
['a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']

Alternative Approach with Empty Subset

If you want to include the empty subset as well, modify the range to start from 0 ?

import itertools

def find_all_subsets(text):
    subsets = []
    for i in range(len(text) + 1):  # Include 0 for empty subset
        for combo in itertools.combinations(text, i):
            subsets.append(''.join(combo))
    return subsets

# Test with empty subset included
text = 'ab'
all_subsets = find_all_subsets(text)
print("All subsets including empty:")
print(all_subsets)
All subsets including empty:
['', 'a', 'b', 'ab']

Conclusion

Using itertools.combinations() provides an efficient way to generate all subsets of a string. The key is to iterate through all possible combination lengths and convert the resulting tuples to strings.

Updated on: 2026-03-27T01:12:58+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements