Why not use a variable list as a parameter, or a variable list as a parameter?

Source: Internet
Author: User

Why not use a variable list as a parameter, or a variable list as a parameter?

The following code:

def test_list(my_list=[]):    my_list.append(1)    return my_listprint(test_list())print(test_list())print(test_list())

Output:

[1][1, 1][1, 1, 1]

 

Intuitively, the output must be [1]. We know that a rule is not to use variable variables as parameters, but why?

 

Function has a built-in function func_defaults that displays the default variables.

>>> test_list.func_defaults([],)

You can see that the func_defaults attribute of the test_list function points to a tuple, which has a [] element, that is, the default value of the function parameter my_list. If it is wrong, the my_list point to the region is variable.

 

Run the evaluate function test_list () and check whether the tuples pointed to by func_defaults have changed.

>>> test_list()[1]>>> test_list.func_defaults([1],)

The default value of my_list is [1]. this is my_list pointing to a variable list, and the python function is passed by reference by default. When the function executes the append operation on my_list, it also changes the list of the tuples pointed to by func_defaults in my_list. During the next execution, the default value of my_list is changed to ([1],).

 

Take a look at python tutor:

 

 

 

 

If the function needs to accept a list, set my_list to None.

def test_list(my_list=None):    if not my_list:        my_list = []    my_list.append(1)    return my_list

 

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.