Search code examples
pythonobjectlambdareducefunctools

An error when redirecting a list of objects to reduce function with lambda


Here is the simple code.

class C:
  def __init__(self):
    self.l = [1,2,3]

a = C()
b = C()
c = C()

reduce(lambda x,y: x.l + y.l, [a,b,c])

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
AttributeError: 'list' object has no attribute 'l'

I know there are several other ways. But I want to see why this doesn't work.

The output should be the same given by

sum([x.l for x in [a,b,c]], [])

which is

[1, 2, 3, 1, 2, 3, 1, 2, 3]

Solution

  • The function passed as the first argument to reduce takes 2 arguments, the first is the result of the previous reduction (or the first item in the iterable if no initial value is given). In your case, after the first 2 lists have been added together x is now a list when passed to the lambda for the second iteration and doesn't have an attribute l as it is not an instance of C

    If you run your list through map you can extract the list from all the objects and pass them to the reduce

    reduce(lambda x, y: x + y, map(lambda z: z.l, [a,b,c]))