Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the reduce function on a list of tuples?

I have this this list of tuple:

  a = [(1, 2), (1, 4), (1, 6)]

I would like to use the reduce function in order to get this result:

  (3, 12)

I tried:

  x = reduce(lambda x, y: x+y, a)

But i get an error...I want to add up all the elements in the first index of each tuple, then add up the second element.

like image 457
Kara Avatar asked Nov 04 '13 07:11

Kara


People also ask

What does reduce () do in Python?

Python's reduce() is a function that implements a mathematical technique called folding or reduction. reduce() is useful when you need to apply a function to an iterable and reduce it to a single cumulative value.

How do you reduce a list in Python?

Python offers a function called reduce() that allows you to reduce a list in a more concise way. The reduce() function applies the fn function of two arguments cumulatively to the items of the list, from left to right, to reduce the list into a single value.

How do you subtract a list of tuples in Python?

Practical Data Science using Python When it is required to subtract the tuples, the 'map' method and lambda function can be used. The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.

How do you get rid of a tuple in a list?

Use the del statement to remove a tuple from a list of tuples, e.g. del list_of_tuples[0] . The del statement can be used to remove a tuple from a list by its index, and can also be used to remove slices from a list of tuples.


2 Answers

If you want the output of a reduce to be a tuple, all the intermediate results should also be a tuple.

a = [(1, 2), (1, 4), (1, 6)]
print reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]), a)

Output

(3, 12)

Edit: If you want to get (0, 0) when the list is empty

a = []
print reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]), [(0, 0)] + a)

Output

(0, 0)

Edit 2: Reduce accepts default initializer as the last parameter, which is optional. By using that, the code becomes

a = []
print reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]), a, (0, 0))
like image 143
thefourtheye Avatar answered Oct 26 '22 19:10

thefourtheye


>>> a = [(1, 2), (1, 4), (1, 6)]
>>> map(sum, zip(*a))
[3, 12]

UPDATE

According to Raymond Hettinger,

zip-star trick abuses the stack to expensively compute a transpose.

Here's an alternative that does not use list comprehension.

>>> a = [(1, 2), (1, 4), (1, 6)]
>>> [sum(item[i] for item in a) for i in range(2)] # 2 == len(a[0])
[3, 12]
>>> a = []
>>> [sum(item[i] for item in a) for i in range(2)] # 2 == len(a[0])
[0, 0]
like image 44
falsetru Avatar answered Oct 26 '22 20:10

falsetru