简体   繁体   中英

Python functions parameter

why append method works on original numbers list and it changed numbers list but I can't reassign numbers list to [4,5,6]?

def change(numbers_list):
    numbers_list.append(4)
    numbers_list = [4,5,6]
numbers = [1,2,3]
change(numbers)
print(numbers)

when code runs this printed:

[1,2,3,4]

why not [4,5,6]?

The function of append is to add an item to an existing list. The reason for no effect is that you are doing many invalid things. For one you are calling the function but never assigning the return to a variable . Second your use of append is void because directly after you declare numbers_list = [4, 5, 6] . If you goal of the function is just to change [1, 2, 3] to [4, 5, 6] the setup would be this.

def change(numbers_list):
    numbers_list = [4,5,6]
    return numbers_list

numbers = [1,2,3]
numbers = change(numbers)
print(numbers)
# [4, 5, 6]

Although this would suffice

numbers = [1, 2, 3]
numbers = [4, 5, 6]
print(numbers)
# [4, 5, 6]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM