python-3.xlistreduceassignment-operatorcompound-assignment

How to use python assignment operator with multiple return values


I have a Python function which takes a parameter and returns 2 outputs. I want to call this for all the elements in a list and combine the return values for each invocation as below:

a1, b1 = func(p[0])
a2, b2 = func(p[1])
a3, b3 = func(p[3])

a = a1 & a2 & a3
b = b1 + b2 + b3

How can I refactor this to a one liner using the += , &= and the reduce operators in Python?

Thanks


Solution

  • We can decompose this problem into individual tasks:

    from functools import reduce
    
    def func(a): return a, a
    p = range(1, 5, 2)
    
    
    def reduction(new, total):
        return new[0] & total[0], new[1] + total[1]
    
    mapped = map(func, p)
    reduced = reduce(reduction, mapped)
    a, b = reduced
    

    If desired, this can be written in one statement/line.

    >>> a, b = reduce(lambda new, total: (new[0] & total[0], new[1] + total[1]), map(func, p))
    >>> a
    1
    >>> b
    4