Computer >> Computer tutorials >  >> Programming >> Python

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


When it is required to find all the combinations in the list with the given condition, a simple iteration, the append method, and the ‘isinstance’ method are used.

Example

Below is a demonstration of the same −

my_list = ["python", [15, 12, 33, 14], "is", ["fun", "easy", "better", "cool"]]

print("The list is :")
print(my_list)

K = 4
print("The value of K is :")
print(K)

my_result = []
count = 0
while count <= K - 1:
   temp = []

   for index in my_list:

      if not isinstance(index, list):
         temp.append(index)
      else:
         temp.append(index[count])
   count += 1
   my_result.append(temp)

print("The result is :")
print(my_result)

Output

The list is :
['python', [15, 12, 33, 14], 'is', ['fun', 'easy', 'better', 'cool']]
The value of K is :
4
The result is :
[['python', 15, 'is', 'fun'], ['python', 12, 'is', 'easy'], ['python', 33, 'is', 'better'], ['python', 14, 'is',
'cool']]

Explanation

  • A list of integers is defined and is displayed on the console.

  • A value for K is defined and is displayed on the console.

  • An empty list is created.

  • A variable ‘count’ is created and is assigned to 0.

  • A while loop is used to iterate over the list, and the ‘isinstance’ method is used to check if the type of element matches a specific type.

  • Depending on this, the element is appended to the empty list.

  • This is the output that is displayed on the console.