7

python中代码运行的困惑

 2 years ago
source link: https://www.mindg.cn/?p=2875
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

python中代码运行的困惑

网上看到的代码:

def clear_list(l):
ll = [1,2,3]
clear_list(ll)
print(ll)

输出是[1,2,3],并不是一个空列表,是不是很奇怪?

首先=号是赋值,而不是改变原列表内容,所以在函数内只是赋值而已,因为在函数内所以 l只是内部变量,函数运行完就消失了,也就是说函数内的变量只是作用域在函数内,所以当函数运行完,并不影响 函数外定义的值,输出仍然是[1,2,3], 如果想实现清除列表功能,改成l.clear()就可以

本条目发布于2022-01-08。属于Python分类。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK