Search code examples
pythonpython-assignment-expression

Python3.8 assignment expressions, use in list comprehension or as an expression


I recently discovered that assignment expressions exist. And I wanted to refactor some of my code to make use of them. Most of the places I wanted to use it were relatively straightforward to convert.

However, I'm not sure of the syntax to use for this particular function. Is there a way I could replace my usage of functools.reduce with assignment expressions?

from functools import reduce

def get_average(xs):
    """
    This function takes in a list of nx3 lists and returns the average
    along each column, returning a 3 length list.
    """
    return [
        x / len(xs)
        for x in reduce(
            lambda acc, x: [sum(z) for z in zip(acc, x)],
            xs,
            [0, 0, 0])]

It's not straightforward to me how to use the result of an assignment expression as an expression directly. Is there a nice and pythonic way to do this?


Solution

  • You don't need assignment expressions here, see this simple list comprehension:

    [sum(i)/len(i) for i in zip(*l)]
    

    example:

    # input
    l = [[1,2,3], [4,5,6]]
    
    # output
    [2.5, 3.5, 4.5]