Search code examples
pythoncombinationspython-itertools

Get all combinations of a list in Python


I would like to get all combinations of a list:

L = ["a","b","c"]
combinations(L,length=2)
# [("a","a"),("a","b"),("a","c"),("b","a"),("b","b"),("b","c"),("c","a"),("c","b"),("c","c")]

I've tried

itertools.combinations()

but this returned

[('a', 'b'), ('a', 'c'), ('b', 'c')]

When I use itertools.permutations(), it just returns the combinations with the length of the iteration, which is also not what I want.

Any librarys / function that I can use, without writing my own?


Solution

  • You can use the second parameter of itertools.permutations():

    from itertools import permutations
    
    L = ["a","b","c"]
    
    print([n for n in permutations(L,2)]+[(i,i) for i in L])
    

    Output:

    [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('a', 'a'), ('b', 'b'), ('c', 'c')]
    

    From the documentation:

    itertools.permutations(iterable, r=None)
    

    Return successive r length permutations of elements in the iterable. If r is not specified or is None, then r defaults to the length of the iterable and all possible full-length permutations are generated.