Python: Create Every Combination of Tuples from a List of Lists Data Structure

Viewed 23

Is there a way to create all possible combinations of a list of lists in tuple form without resorting to nested for loops?

I have the following variable:

test_list = [['hugs'], ['yelling', 'fighting', 'kicking'], ['love', 'care']]

I want to create the following output but without using nested for loops: enter image description here

Is there a way to do this? I'd prefer not to have to import a library if possible.

1 Answers

this may help

import itertools

test_list = [['hugs'], ['yelling', 'fighting', 'kicking'], ['love', 'care']]
mylist = itertools.product(test_list, repeat=2)
print(list(mylist))

result : [(['hugs'], ['hugs']), (['hugs'], ['yelling', 'fighting', 'kicking']), (['hugs'], ['love', 'care']), (['yelling', 'fighting', 'kicking'], ['hugs']), (['yelling', 'fighting', 'kicking'], ['yelling', 'fighting', 'kicking']), (['yelling', 'fighting', 'kicking'], ['love', 'care']), (['love', 'care'], ['hugs']), (['love', 'care'], ['yelling', 'fighting', 'kicking']), (['love', 'care'], ['love', 'care'])]

Related