Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python reduce explanation

I'm not able to understand the following code segment:

>>> lot = ((1, 2), (3, 4), (5,))
>>> reduce(lambda t1, t2: t1 + t2, lot)
(1, 2, 3, 4, 5)

How does the reduce function produce a tuple of (1,2,3,4,5) ?

like image 519
Sibi Avatar asked Nov 28 '12 10:11

Sibi


People also ask

What is the use of reduce () function?

The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

What is accepted by the reduce () function as argument in Python?

The reduce function can take in three arguments, two of which are required. The two required arguments are: a function (that itself takes in two arguments), and an iterable (such as a list). The third argument, which is an initializer, is optional and thus we will discuss it later on.

What is reduce in programming?

In computer science, the reduction operator is a type of operator that is commonly used in parallel programming to reduce the elements of an array into a single result. Reduction operators are associative and often (but not necessarily) commutative.

How do you make a function reduce in Python?

Reduce function is an inbuilt function in python whose major task is to give aggregate value as an output. Syntactically it is written as; reduce(func,iter_obj) here reduce operation will be done on “func” function and “iter_obj” is implying the iterable data values used to return result of output.


1 Answers

It's easier if you break out the lambda into a function, so it's clearer to what's going on:

>>> def do_and_print(t1, t2):
    print 't1 is', t1
    print 't2 is', t2
    return t1+t2

>>> reduce(do_and_print, ((1,2), (3,4), (5,)))
t1 is (1, 2)
t2 is (3, 4)
t1 is (1, 2, 3, 4)
t2 is (5,)
(1, 2, 3, 4, 5)
like image 154
Jon Clements Avatar answered Sep 23 '22 07:09

Jon Clements