Open In App

All Combinations For A List Of Objects

Prerequisite: Python Itertools

There are several ways to get all combinations for a list of objects in python. This problem has already a recursive solution. Python has an itertools module that provides two functions named combinations() and combinations_with_replacement() which make our work a lot easier. Below are the two methods:



1. Using itertools.combinations():

Syntax : itertools.combination(iterable, r)  

Where r is the length of output tuples.



This function returns subsequences(tuples) of length r from the input iterable. It takes a list of objects and the length of the output tuples(r) as input. But there are a few things to notice about this function like:

All combinations without replacement

Below is the implementation:




# code
from itertools import combinations
  
# m = list of objects.
# same method can be applied 
# for list of integers.
m = ['GFG', 'GeeksforGeeks', 'Geeks']
# display
for i in range(len(m)):
  print(list(combinations(m, i+1)))

Output:

[('GFG',), ('GeeksforGeeks',), ('Geeks',)]
[('GFG', 'GeeksforGeeks'), ('GFG', 'Geeks'), ('GeeksforGeeks', 'Geeks')]
[('GFG', 'GeeksforGeeks', 'Geeks')]

If the input has duplicate elements:




# code
from itertools import combinations
  
# m = list of objects.
# 1st and 3rd elements are same. 
# same method can be applied 
# for list of integers.
m = ['GFG', 'GeeksforGeeks', 'GFG']
  
# output : list of combinations.
for i in range(len(m)):
  print(list(combinations(m, i+1)))

Output:

[('GFG',), ('GeeksforGeeks',), ('GFG',)]
[('GFG', 'GeeksforGeeks'), ('GFG', 'GFG'), ('GeeksforGeeks', 'GFG')]
[('GFG', 'GeeksforGeeks', 'GFG')]

2. Using itertools.combinations_with_replacement():

Syntax: itertools.combination_with_replacement(iterable, r) 

 Where r is the length of output tuples.

This function works same as itertools.combinations(). But this function returns r length subsequences including individual elements repeated more than once. There are also some points to note:

Combinations with replacement.

Below is the implementation:




# code
from itertools import combinations_with_replacement
  
# m = list of objects.
# same method can be applied 
# for list of integers.
m = ['GFG', 'GeeksforGeeks', 'Geeks']
  
# output : list of combinations.
for i in range(len(m)):
  print(list(combinations_with_replacement(m, i+1)))

Output:

[(‘GFG’,), (‘GeeksforGeeks’,), (‘Geeks’,)]
[(‘GFG’, ‘GFG’), (‘GFG’, ‘GeeksforGeeks’), (‘GFG’, ‘Geeks’), (‘GeeksforGeeks’, ‘GeeksforGeeks’), (‘GeeksforGeeks’, ‘Geeks’), (‘Geeks’, ‘Geeks’)]
[(‘GFG’, ‘GFG’, ‘GFG’), (‘GFG’, ‘GFG’, ‘GeeksforGeeks’), (‘GFG’, ‘GFG’, ‘Geeks’), (‘GFG’, ‘GeeksforGeeks’, ‘GeeksforGeeks’), (‘GFG’, ‘GeeksforGeeks’, ‘Geeks’), (‘GFG’, ‘Geeks’, ‘Geeks’), (‘GeeksforGeeks’, ‘GeeksforGeeks’, ‘GeeksforGeeks’), (‘GeeksforGeeks’, ‘GeeksforGeeks’, ‘Geeks’), (‘GeeksforGeeks’, ‘Geeks’, ‘Geeks’), (‘Geeks’, ‘Geeks’, ‘Geeks’)]


Article Tags :