user3200392 user3200392 - 17 days ago 5
Python Question

Generate all possible 2 and 3 string combinations from a list in python

I have a following list:

mylist = ['car', 'truck', 'ship']


Currently I am able to only get all the possible combinations of 2 strings using this:

from itertools import combinations
print(list(combinations(mylist,2)))


which gives me:

[('car', 'truck'), ('car', 'ship'), ('truck', 'ship')]


However, one combination is actually all the 3 strings. Thus I would like my outcome to be:

[('car', 'truck'), ('car', 'ship'), ('truck', 'ship'), ('car', 'truck', 'ship')]

Answer

This is an adjusted case of the powerset. Typically the code for the powerset in Python looks like this:

from itertools import chain, combinations

def powerset(it):
    yield from chain.from_iterable(combinations(it, r) for r in range(len(it)+1))

You can change it, though, to only accept results within a certain range. In your case, it's from 2 to the 3:

from itertools import chain, combinations

def adjusted_powerset(it):
    yield from chain.from_iterable(combinations(it, r) for r in range(2, 3))

See it in action here.

If you need it to become more general, play with the range parameters. A nice template would be to create a powerset helper:

from itertools import chain, combinations

def powerset_helper(it, start, stop):
    yield from chain.from_iterable(combinations(it, r) for r in range(start, stop+1))

def powerset(it):
    yield from powerset_helper(it, 0, len(it))

def adjusted_powerset(it):
    yield from powerset_helper(it, 2, 3)