Python – All replacement combination from other list

PythonServer Side ProgrammingProgramming

When it is required to get the replacement combination from the other list, the ‘combinations’ method and the ‘list’ method is used.

Example

Below is a demonstration of the same

from itertools import combinations

my_list = [54, 98, 11]

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

replace_list = [8, 10]

my_result = list(combinations(my_list + replace_list, len(my_list)))

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

Output

The list is :
[54, 98, 11]
The result is :
[(54, 98, 11), (54, 98, 8), (54, 98, 10), (54, 11, 8), (54, 11, 10), (54, 8, 10), (98, 11, 8), (98, 11, 10), (98, 8, 10), (11, 8, 10)]

Explanation

  • The required packages are imported into the environment.

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

  • Another replace list is defined.

  • The 'combinations' method is used to concatenate the original list, the replace list, and the length of the original list.

  • This is converted to a list.

  • This is assigned to a variable.

  • The result is displayed on the console.

raja
Published on 16-Sep-2021 08:51:09
Advertisements