Please explain the logic | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Please explain the logic

import functools list=[1,2,3,4,5] R_list=[functools.reduce(lambda x,y: x*y,list)] print(R_list)

11th Oct 2018, 7:26 AM
AMAN TOMAR
AMAN TOMAR - avatar
4 Answers
+ 6
functools.reduce(function, iterable[, initializer]) Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). Source: https://docs.python.org/3/library/functools.html
11th Oct 2018, 7:57 AM
Anna
Anna - avatar
+ 3
functools.reduce execute a function with items of an iterable by passing couple of parameter starting from left to right of iterable then passing the result of function and next item for next function call while all items are processed, then return the result. In yourexample, this happen: 1) first two items are multiplied 1*2=2 2) the result is multiplied for 3rd items 2*3= 6 3) the result is multiplied for 4th items 6*4= 24 4) the result is multiplied for 5th items 24*5= 120 5) functools.reduce return 120 For more details see here https://docs.python.org/3/library/functools.html
11th Oct 2018, 8:01 AM
KrOW
KrOW - avatar
+ 3
thank you KrOW Anna
11th Oct 2018, 8:07 AM
AMAN TOMAR
AMAN TOMAR - avatar
11th Oct 2018, 7:26 AM
AMAN TOMAR
AMAN TOMAR - avatar