LearnFrenzy
Sign in Take a free test

Lambda Functions · Predict the Output · Question 5

reduce() with and without an initial value Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

What is the output of the following Python program?

main.py
from functools import reduce

print(reduce(lambda a, b: a * b, [1, 2, 3, 4]), reduce(lambda a, b: a + b, ["x", "y"], "->"))
print(reduce(lambda a, b: a if a > b else b, [3, 9, 4]))
  • A 10 ->xy 9
  • B 24 ->xy 9 Correct
  • C 24 xy-> 3
  • D 24 ->x->y 9
Correct Answer: Option B

1·2·3·4 = 24. The initial value "->" is the first accumulator. The last reduce keeps the larger value at each step.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links