The pit "closure and lambda" in Python

Source: Internet
Author: User
Tags closure

First look at a chestnut:

DEF create ():    return [Lambda x:i*x for I in range (5)]for I in Create ():    Print (I (2))

Results:

88888

The return value of the CREATE function is a list, and each element of the list is a function-a function that multiplies the input parameter x by a multiplier of I. The expected results are 0,2,4,6,8. But the result is 5 8, not surprisingly.

Because lambda is often used when this trap occurs, it may be considered a lambda problem, but Lambda says it is reluctant to carry the pot. The nature of the problem in Python with the attribute lookup rule, LEGB (Local,enclousing,global,bulitin), in the above example,I is in the closure scope (enclousing), and Python's closure is late binding, This means that the value of the variable used in the closure is the query obtained when the internal function is invoked.

The solution is also very simple, that is, the scope of the closure of the domain is a local scope.

DEF create ():    return [Lambda x, i=i:i*x for I in range (5)]for I in Create ():    Print (I (2))

To change the way:

DEF create ():    a = [] for    I in range (5):        def demo (x):            return x*i        a.append (demo)    return afor I in CR Eate ():    Print (I (2))

Both of these are the same.

Results:

02468

---_<_>_---

One more question. Similar chestnuts

The code is simple: (declaration: Python3 problem)

Nums = Range (2,20) for I in nums:    nums = filter (lambda x:x==i or x%i, nums) print (list (nums))

There's another way of writing it.

DEF create ():    a = [] for    I in range (5):        def demo (x,i=i):            return x*i        a.append (demo)    return afor I In Create ():    Print (I (2))

Results:

[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

The same as normal logical results should be:

[2, 3, 5, 7, 11, 13, 17, 19]

The cause of the problem:

    • In Python3, the filter () function returns an iterator, so it does not perform the actual execution, but executes at each invocation (the list of values returned by the filter () in Python2, no such phenomenon)
    • After the traversal of the execution of the printing, now execute the function in the loop, with the above a chestnut problem, I this variable using the last call when the value, and the above chestnut is different from the above chestnut is the value of the inline scope, and this chestnut is the value of the global I

To modify the code:

Nums = Range (2,20) for I in nums:    nums = filter (lambda x,i=i:x==i or x%i, nums) print (list (nums))

Results:

[2, 3, 5, 7, 11, 13, 17, 19]

Find out more---_<_>_---

The pit "closure and lambda" in Python

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.