Search code examples
pythonlistpython-itertools

Create list with combinations of 3 elements of other list with repetitions


I have a list with some elements and I want to create a list where I combine this items 3 by 3. Until now I managed to do this but I can't figure how can I do combinations with repeated elements. So far the code I have is this one:

list_of_aa = ["A", "R", "N", "D", "C", "Q", "E", "G", "H", "I", "L", "K", "M", "F", "P", "S", "T", "W", "Y", "V"]

combinations = list(itertools.combinations(list_of_aa, 3))

But with this code I'm missing triplets like "AAA" or "MAA". Do you have any idea how can I solve this problem? Thanks in regard.


Solution

  • You want to have the cartesian product of your items, so use itertools.product():

    itertools.product(list_of_aa, repeat=3)
    

    Note that this produces len(list_of_aa) ** 3 (so the cube) number of elements, you may want to avoid materialising that all into a list. For your sample input, 8000 3-element tuples are produced.

    Demo taking slices out of the whole result:

    >>> from itertools import product, islice
    >>> list_of_aa = ["A", "R", "N", "D", "C", "Q", "E", "G", "H", "I", "L", "K", "M", "F", "P", "S", "T", "W", "Y", "V"]
    >>> for combo in islice(product(list_of_aa, repeat=3), 5):
    ...     print(''.join(combo))
    ...
    AAA
    AAR
    AAN
    AAD
    AAC
    >>> for combo in islice(product(list_of_aa, repeat=3), 1000, 1005):
    ...     print(''.join(combo))
    ...
    NLA
    NLR
    NLN
    NLD
    NLC
    >>> for combo in islice(product(list_of_aa, repeat=3), 2000, 2005):
    ...     print(''.join(combo))
    ...
    QAA
    QAR
    QAN
    QAD
    QAC