Home > Mobile >  How generate all possible combinations adding items from one list to another in python?
How generate all possible combinations adding items from one list to another in python?

Time:01-06

I have two lists:

list1 = ["a", "b"]
list2 = ["item1", "item2", "item3", "item4"] 

How can I add items from list2 to the list1 to generate all possible combinations with different length. Items from the list1 must always appear complete and at the beginning.

Expected output:

result = [["a", "b", "item1"], 
          ["a", "b", "item2"], 
          ["a", "b", "item1", "item2"], 
          ["a", "b", "item1", "item2", "item4"], 
          ["a", "b", "item3", "item4", "item2", "item1"], 
          ...]

It is also not required to have several lists that have the same items only the order of items is different. Ex:

[["a", "b", "item1", "item2"], ["a", "b", "item2", "item1"]]

CodePudding user response:

The itertools.combinations is your friend here.

Note: I only added the combinations to another list, powerset, for exemplary purposes. In many cases, the number of combinations may be huge, and if you were to process the combinations somehow, you would probably want to process each combination separately and not save them to a list. Unless that's your end goal.

import itertools 

list1 = ["a", "b"]
list2 = ["item1", "item2", "item3", "item4"] 

powerset = []
for k in range(1, len(list2) 1):
    for combination in itertools.combinations(list2, k):
        powerset.append(list1   list(combination))

Resulting powerset:

[['a', 'b', 'item1'],
 ['a', 'b', 'item2'],
 ['a', 'b', 'item3'],
 ['a', 'b', 'item4'],
 ['a', 'b', 'item1', 'item2'],
 ['a', 'b', 'item1', 'item3'],
 ['a', 'b', 'item1', 'item4'],
 ['a', 'b', 'item2', 'item3'],
 ['a', 'b', 'item2', 'item4'],
 ['a', 'b', 'item3', 'item4'],
 ['a', 'b', 'item1', 'item2', 'item3'],
 ['a', 'b', 'item1', 'item2', 'item4'],
 ['a', 'b', 'item1', 'item3', 'item4'],
 ['a', 'b', 'item2', 'item3', 'item4'],
 ['a', 'b', 'item1', 'item2', 'item3', 'item4']]

Short explanation

From the docs: The itertools.combinations(iterable, r) yields all r length subsequences of elements from the input iterable. The iterable can be any iterable, like a list or a tuple.

In general iterable is any python object with the __iter__ method that returns an iterator (an object which implements __next__); iterables can be looped over with for loops.

  • Related