Search code examples
pythonlistpermutation

Python: Iterating through a list and returning a tuple permutation for all strings in the list?


I have a list of elements: list = ['A','B',C']. How do I iterate through this list and return the following: [AB, AC, BC]?

note: I only want unique pairs, not [AA, BB, CC...] or [AB, BA, BC, CB...]


Solution

  • You need itertools.combinations:

    In [1]: from itertools import combinations
    
    In [2]: for c in combinations(['A', 'B', 'C'], 2):
       ...:     print(c)
       ...: 
    ('A', 'B')
    ('A', 'C')
    ('B', 'C')