Search code examples
pythonlistfor-looplist-comprehension

Automatically send all elements in list inside of a for loop list comprehension into a function


I access a function via this list comprehension and have made it work by explicitly creating a variable for each element of the list_of_lists. I want a better way to access the elements in the function in a list comprehension. Example:

list_of_lists = [[0, 1, 2, 3], [0, 1, 2, 3], ...]

[function(i, j, k, l) for i, j, k, l in list_of_lists]

It's a very annoying syntax as I need to update (i, j, k, l) for i, j, k, l if the number of elements in a sub-list of list_of_lists changes.

E.g., a change to [[0, 1, 2, 3, 4, 5, 6], ...] needs the syntax to be (i, j, k, l, m, n) for i, j, k, l, m, n and I need to be sure I do not miscount. This gets worse for more elements per sub-list and if the function changes during coding.

Is there a way to say something like:

[function(*) for * in list_of_lists]

So my woes are ameliorated?

I tried searching for something like this but it's clear I don't know the right words to be able to search this.


Solution

  • You're looking for * to unpack the list
    https://peps.python.org/pep-3132/

    [function(*sublist) for sublist in list_of_lists]
    
    >>> def foo(a, b, c, d):
    ...     return a + b + c + d
    ... 
    >>> lst = [1, 2, 3, 4]
    >>> foo(*lst)  # iterable unpack
    10
    >>> d = {'a':1, 'b':2, 'c':3, 'd':4}
    >>> foo(**d)   # dict unpack
    10