aelin_s
0
Q:

python reduce()

from functools import reduce
items = [1,2,3,4,5]
sum_all = reduce(lambda x,y: x + y, items)
 
print (sum_all) #15
3
'''try this'''
from functools import reduce
a = [1,2,3,4]

SUM = reduce(lambda n,n2:n+n2,a)

print(SUM)
4
#max num in list
from functools import reduce
items = [1, 24, 17, 14, 9, 32, 2]
all_max = reduce(lambda a,b: a if (a > b) else b, items)
 
print (all_max) # 32
1
# python code to demonstrate working of reduce() 
# using operator functions 
  
# importing functools for reduce() 
import functools 
  
# importing operator for operator functions 
import operator 
  
# initializing list 
lis = [ 1 , 3, 5, 6, 2, ] 
  
# using reduce to compute sum of list 
# using operator functions 
print ("The sum of the list elements is : ",end="") 
print (functools.reduce(operator.add,lis)) 
  
# using reduce to compute product 
# using operator functions 
print ("The product of list elements is : ",end="") 
print (functools.reduce(operator.mul,lis)) 
  
# using reduce to concatenate string 
print ("The concatenated product is : ",end="") 
print (functools.reduce(operator.add,["geeks","for","geeks"])) 
3

New to Communities?

Join the community