Python use list as default parameter in function

One of the pitfalls of Python encountered in learning is to use lists as default parameters.

We know that in Python, lists are mutable objects, so the contents of the list may change within the function. Another thing to be aware of is how the contents of the list change when using a list as the default parameter of a function.

First, let's look at the following code example:

def add(x, lst=[]):
    if x not in lst:
        lst.append(x)

    return lst

def main():
    list1 = add(1)
    print(list1)

    list2 = add(2)
    print(list2)

    list3 = add(3, [11, 12, 13, 14])
    print(list3)

    list4 = add(4)
    print(list4)

main()

You might expect the output to be:

[1]
[2]
[11, 12, 13, 14, 3]
[4]

But in fact, the output of the program is:

[1]
[1, 2]
[11, 12, 13, 14, 3]
[1, 2, 4]

Why is this? The function of the function add is to append x to the list lst when x is not in the list. When the function is executed for the first time, a default value [] for the parameter lst is created. This default value will only be created once. add(1) adds 1 to lst.

When the function is called again, lst is [1] instead of [] because lst is only created once. When the lst of the parameter is [11, 12, 13, 14], the lst is [11, 12, 13, 14]. When list4 calls the function, it uses default parameters, so now the default parameter lst is [1,2].

In order to better understand the calling situation, you can output the id of lst in the add function, such as the following code:

def add(x, lst=[]):
    print(id(lst))

    if x not in lst:
        lst.append(x)
    
    return lst

def main():
    list1 = add(1)
    print(list1)

    list2 = add(2)
    print(list2)

    list3 = add(3, [11, 12, 13, 14])
    print(list3)

    list4 = add(4)
    print(list4)

main()

The output is as follows:

4469603648
[1]
4469603648
[1, 2]
4469670472
[11, 12, 13, 14, 3]
4469603648
[1, 2, 4]

It can be seen that the id of the default parameter has not changed when list1, list2, and list4 are called, while the id of list3 has changed.

This is a pitfall of Python's use of lists as default arguments. So, how to avoid stepping on the pit? If you want to use the default list to be [] on every function call, you can modify the function parameters like the following program:

def add(x, lst=None):

    if lst is None:
        lst = []
    if x not in lst:
        lst.append(x)

    return lst

def main():
    list1 = add(1)
    print(list1)

    list2 = add(2)
    print(list2)

    list3 = add(3, [11, 12, 13, 14])
    print(list3)

    list4 = add(4)
    print(list4)

main()

The output is as follows:

[1]
[2]
[11, 12, 13, 14, 3]
[4]

Guess you like

Origin blog.csdn.net/m0_67575344/article/details/124283730
Recommended