Search code examples
pythonlistnestedlist-comprehension

List comprehension as multi-line


I am learning Python and trying to understand how to write the list comprehension in the following code as multi-line code. I am just lost as I haven't seen the variable called inside its own comprehension before.

list_of_lists = [['a','b','c','d'],[1,2,3]]

result = [[]]
  for l in list_of_lists:
    result = [x+[y] for x in result for y in l]

Solution

  • Your code is roughly equivalent to the following code. Note the order of the for-loop on result and the for-loop on l.

    list_of_lists = [['a','b','c','d'],[1,2,3]]
    
    result = [[]]
    for l in list_of_lists:
        new_result = []
        for x in result:
            for y in l:
                new_product = x + [y]
                new_result.append(new_product)
        result = new_result
    

    You can read more about list comprehensions in the Python documentation. It has another example of double use of for in one list comprehension.

    For example, this listcomp combines the elements of two lists if they are not equal:

    >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
    [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
    

    and it’s equivalent to:

    >>> combs = []
    >>> for x in [1,2,3]:
    ...     for y in [3,1,4]:
    ...         if x != y:
    ...             combs.append((x, y))
    ...
    >>> combs
    [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]