Search code examples
pythontuplespython-itertoolsnested-lists

Combinations by list in nested lists in Python


I have a list of the form [['a','b','c','d'], ['a','c','d'], ['b','d','e','f','g','h'], ... ,['c','d','a','b']] and I have to combine the elements of each nested list (separately) in 2-tuples to form a single 2-tuples' list. I have tried to do it with the following code but it only combines the elements of the first list:

def totwotuples(my_list):
    for i in range(len(my_list)):
        for j in range(len(my_list[i])):
           twotuples = itertools.combinations(my_list[i], 2)
    return[k for k in twotuples]

How can I iterate over all nested lists? in order to get this expected output (e.g. for first two nested lists): [('a','b'), ('a','c'), ('a','d'), ('b','c'), ('b','d'), ('c','d'), ('a','c'), ('a','d'), ('c','d'), ...]


Solution

  • You can use itertools.chain or itertools.chain.from_iterable to combine the results from sublists.

    import itertools
    
    lst = [['a','b','c','d'], ['a','c','d']]
    
    output = itertools.chain.from_iterable(itertools.combinations(sublst, r=2) for sublst in lst)
    output = list(output) # convert to a list
    print(output) # [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd'), ('a', 'c'), ('a', 'd'), ('c', 'd')]