Reduce in Python

Source: Internet
Author: User

When I searched for a factorial using Python today, the simplest found was to use the reduce built-in function, but when I was using reduce, I reported nameerror: name 'reduce' is not defined. so I searched again and found that after Python 3.0.0.0, reduce is no longer in the built-in function. To use it, I have to import reduce from functools.

For details, seeThe fate of reduce () in Python 3000.

 

Reduce usage

Reduce (function, sequence [, initial])-> Value

Apply a function of two arguments cumulatively to the items of a 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). If initial is present, it is placed before the items
Of the sequence in the calculation, and serves as a default when
Sequence is empty.

 

This means that the function is used continuously for sequence. If initial is not given, two elements of sequence will be transferred for the first call, and the result of the previous call and the next element of sequence will be passed to the function. if initial is given, the first element of initial and sequence is passed to the function for the first time.

 

>>> From functools import reduce <br/> reduce (lambda X, Y: X + Y, [1, 2, 3]) <br/> 6 <br/> reduce (lambda X, Y: X + Y, [1, 2], 9) <br/> 15 <br/> reduce (lambda X, Y: X + Y, [1, 2, 3], 7) <br/> 13 <br/>

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.