首页 > 解决方案 > 为什么在函数中传递的 list 的值没有得到更新?

问题描述

def mystery(l):
  l = l[0:5] #<-problem here
  return()

list1 = [44,71,12,8,23,17,16]
mystery(list1)

当我打印 list1 时,答案是 [44,71,12,8,17,16]。为什么 list1 没有在 l=l[0:5] 行更新,因为列表是可变的?

标签: python-3.xlistfunction

解决方案


l是局部变量;分配给一个名称永远不会改变它曾经引用的对象。如果要截断 引用的列表l,则需要使用类似

l[:] = l[0:5]  # Replace the contents of the list with just the first 5

或更简单地说

del l[5:]  # Remove all but the first 5 elements

推荐阅读