Python: All possible combinations of the elements of a given list
Python List: Exercise - 149 with Solution
Write a Python program to get all possible combinations of the elements of a given list.
Sample Solution:
Python Code:
# Define a function 'combinations_list' to generate all possible combinations of a list's elements
def combinations_list(colors):
# Base case: if the input list 'colors' is empty, return a list containing an empty list
if len(colors) == 0:
return [[]]
result = []
# Recursive case: for each element in the list, generate combinations with and without the element
for el in combinations_list(colors[1:]):
result += [el, el + [colors[0]]]
return result
# Create a list 'colors' with elements
colors = ['orange', 'red', 'green', 'blue']
# Print a message indicating the original list
print("Original list:")
# Print the contents of 'colors'
print(colors)
# Print a message indicating the operation to generate all possible combinations
print("\nAll possible combinations of the said list’s elements:")
# Call the 'combinations_list' function with 'colors' and print the result
print(combinations_list(colors))
Sample Output:
Original list: ['orange', 'red', 'green', 'blue'] All possible combinations of the said list's elements: [[], ['orange'], ['red'], ['red', 'orange'], ['green'], ['green', 'orange'], ['green', 'red'], ['green', 'red', 'orange'], ['blue'], ['blue', 'orange'], ['blue', 'red'], ['blue', 'red', 'orange'], ['blue', 'green'], ['blue', 'green', 'orange'], ['blue', 'green', 'red'], ['blue', 'green', 'red', 'orange']]
Flowchart:
Python Code Editor:
Previous: Write a Python program to remove specific words from a given list.
Next: Write a Python program to reverse a given list of lists.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/list/python-data-type-list-exercise-149.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics