A list in Python as a default parameter trap

Source: Internet
Author: User

In python, as the default parameter must be immutable object, if it is a mutable object, there will be problems, a little attention, will be transferred into traps, especially beginners, such as I (┬_┬).

Let's look at an example.

1 defAdd (l=[]):2L.append (1)3     returnL4 5L = [1, 2, 3]6NEWL =Add (L)7 Print(NEWL)8NEWL =Add (NEWL)9 Print(NEWL)Ten  OneTestl =Add () A Print(TESTL) -Testl =Add () - Print(TESTL) theTestl =Add () - Print(TESTL)

Run results

  

When the parameters are passed in normally, there seems to be no big problem. But when we use the default parameters, the problem arises.

The results of the operation did not appear as we expected. Why?

When we call a function, if there is a pass parameter, the passed argument is used, and if no argument is passed, the default argument is used. when using default parameters, the same is used, that is, the last default parameter value saved. We can verify this by printing the ID.

  

Therefore, the default parameter must be immutable , and if it is a mutable object, this will happen.

So how to solve it?

We can let L point to the immutable variable of None, and then add a judgment to let the default parameter return to the position .

1 defAdd (l=None):2     if(L = =None):3L = []4L.append (1)5     returnL6 7L = [1, 2, 3]8NEWL =Add (L)9 Print(NEWL)TenNEWL =Add (NEWL) One Print(NEWL) A  -Testl =Add () - Print(TESTL) theTestl =Add () - Print(TESTL) -Testl =Add () - Print(TESTL)

  

This way, we solve the trap, then next time should not fall into the, you say?

  Remember: The default parameter is to use immutable objects!!!

Immutable (immutable):int,string,float, number,tuple

Variable (mutable):dictionary,list,set

A list in Python as a default parameter trap

Related Article

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.