Python 列表修改:函数参数传递与列表修改

示例代码:

def changeList(list):
    list.append('end')
print('list', list)
strs = ['1', '2']
changeList(strs)
print('strs', strs)

问题:

上面代码中,对 strs 和 list 的值输出正确的是?( ) A)strs ['1', '2', 'end'] list ['1', '2', 'end'] B)strs ['1', '2'] list ['1', '2', 'end'] C)strs ['1', '2', 'end'] list ['1', '2'] D)strs ['1', '2'] list ['1', '2']

答案: A

解析:

函数 changeList 接收一个列表参数 list,将字符串 'end' 添加到 list 末尾,然后输出 list。在主程序中,定义了一个字符串列表 strs,其值为 ['1', '2'],然后调用函数 changeList,将 strs 作为参数传入。

由于 Python 中函数参数传递是引用传递,所以函数内部修改 list 实际上是修改了 strs 指向的列表对象。因此,函数执行后,strs 的值变为 ['1', '2', 'end']。最后输出 strslist 的值,因此答案为 A。

总结:

在 Python 中,函数参数传递是引用传递,这意味着函数内部修改参数列表实际上是修改了外部列表对象。

Python 列表修改:函数参数传递与列表修改

原文地址: https://www.cveoy.top/t/topic/f2DO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录