VOOZH about

URL: https://www.geeksforgeeks.org/python/python-program-to-find-all-the-combinations-in-the-list-with-the-given-condition/

⇱ Python program to find all the Combinations in the list with the given condition - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python program to find all the Combinations in the list with the given condition

Last Updated : 24 Aug, 2022

Given a list with some elements being a list of optional elements. The task is to find all the possible combinations from all options.

Examples:

Input: test_list = [1,2,3] 
Output
 [1], [1, 2], [1, 2, 3], [1, 3]
 [2], [2, 3], [3]

Example 1: Get all possible combinations of a list’s elements using combinations

Output:

Combination 1 : ('GFG', [5, 4])
Combination 2 : ('GFG', 'is')
Combination 3 : ('GFG', ['best', 'good', 'better', 'average'])
Combination 4 : ([5, 4], 'is')
Combination 5 : ([5, 4], ['best', 'good', 'better', 'average'])
Combination 6 : ('is', ['best', 'good', 'better', 'average'])

Example 2: Get all possible combinations of a list’s elements using combinations_with_replacement

Output:

Combination 1 : ('GFG', 'GFG')
Combination 2 : ('GFG', [5, 4])
Combination 3 : ('GFG', 'is')
Combination 4 : ('GFG', ['best', 'good', 'better', 'average'])
Combination 5 : ([5, 4], [5, 4])
Combination 6 : ([5, 4], 'is')
Combination 7 : ([5, 4], ['best', 'good', 'better', 'average'])
Combination 8 : ('is', 'is')
Combination 9 : ('is', ['best', 'good', 'better', 'average'])
Combination 10 : (['best', 'good', 'better', 'average'], ['best', 'good', 'better', 'average'])

Example 3: Get all possible combinations of a list’s elements using loop

In this, we use a nested loop to get index wise combinations from each nested option list, and then the outer loop is used to get default values in all combinations.

Output:

(2, 3)
(2, 1)
(2, 6)
(2, 4)
(2, 7)
(3, 1)
(3, 6)
(3, 4)
(3, 7)
(1, 6)
(1, 4)
(1, 7)
(6, 4)
(6, 7)
(4, 7)

Example 4: Get all possible combinations of a list’s elements using recursion

Output:

(2, 3)
(2, 1)
(2, 6)
(2, 4)
(2, 7)
(3, 1)
(3, 6)
(3, 4)
(3, 7)
(1, 6)
(1, 4)
(1, 7)
(6, 4)
(6, 7)
(4, 7)
Comment