Search code examples
pythonzip

Creating a list of tuples of different lists


Let's assume that I have the following three lists (l1, l2, l3). How can I create a new list where each element is a tuple of elements of the lists (l_desired)? It actually works as an extended version of the zip method in python.

In simpler words, given l1, l2, l3, how can I create l_desired?

l1 = [1,2,3]
l2 = ['a', 'b', 'c']
l3 = ['Jess', 'Muss']

l_desiered = [(1, 'a', 'Jess'), (1, 'b', 'Jess'), (1, 'c', 'Jess'), 
              (1, 'a', 'Muss'), (1, 'b', 'Muss'), (1, 'c', 'Muss'), 
              (2, 'a', 'Jess'), (2, 'b', 'Jess'), (2, 'c', 'Jess'), ...]

`


Solution

  • As others have already said, use itertools.product():

    >>> l1 = [1,2,3]
    >>> l2 = ['a', 'b', 'c']
    >>> l3 = ['Jess', 'Muss']
    >>> list(itertools.product(l1, l2, l3))
    [(1, 'a', 'Jess'), (1, 'a', 'Muss'), (1, 'b', 'Jess'), (1, 'b', 'Muss'), (1, 'c', 'Jess'), (1, 'c', 'Muss'), (2, 'a', 'Jess'), (2, 'a', 'Muss'), (2, 'b', 'Jess'), (2, 'b', 'Muss'), (2, 'c', 'Jess'), (2, 'c', 'Muss'), (3, 'a', 'Jess'), (3, 'a', 'Muss'), (3, 'b', 'Jess'), (3, 'b', 'Muss'), (3, 'c', 'Jess'), (3, 'c', 'Muss')]
    

    To achieve the sort order specified in your question, you can sort the results like this:

    >>> from operator import itemgetter
    >>> sorted(itertools.product(l1, l2, l3), key=itemgetter(0,2,1))
    [(1, 'a', 'Jess'), (1, 'b', 'Jess'), (1, 'c', 'Jess'), (1, 'a', 'Muss'), (1, 'b', 'Muss'), (1, 'c', 'Muss'), (2, 'a', 'Jess'), (2, 'b', 'Jess'), (2, 'c', 'Jess'), (2, 'a', 'Muss'), (2, 'b', 'Muss'), (2, 'c', 'Muss'), (3, 'a', 'Jess'), (3, 'b', 'Jess'), (3, 'c', 'Jess'), (3, 'a', 'Muss'), (3, 'b', 'Muss'), (3, 'c', 'Muss')]