为什么在Python中无法用for in循环修改列表元素?
为什么两段列表循环代码的修改效果不同?
第一段可修改原列表的代码
numbers = [42, 123] numbers[1] = 5 for index in range(len(numbers)): print(numbers[index]) numbers[index] = numbers[index] * 2 print(numbers[index]) print(numbers)
输出:
84 10 [84, 10]
这段代码通过索引直接访问列表元素,numbers[index] = ...的操作是直接修改列表容器对应位置的元素引用,所有改动都会直接作用于原列表,因此最终列表内容会被更新。
第二段无法修改原列表的代码
for number in numbers: number = number * 2 print(number) print(numbers)
输出:
84 10 [42, 5]
你的猜想完全正确:for...in循环中的number是一个局部变量,它只是临时拷贝了列表当前元素的值(对于整数这类不可变类型,就是值的复制)。执行number = number * 2时,只是改变了这个局部变量的指向(指向新生成的整数对象),完全没有触及原列表内部的元素引用,所以原列表不会发生任何变化。
补充说明:可变对象的情况
如果列表存储的是可变对象(比如字典、列表),for...in循环中修改对象的内部属性时,原列表会跟着变化,但重新给循环变量赋值依然不会影响原列表:
items = [{"value": 1}, {"value": 2}] for item in items: item["value"] *= 2 # 修改可变对象的属性,原列表同步更新 print(items) # 输出: [{'value': 2}, {'value': 4}] for item in items: item = {"value": 0} # 重新赋值局部变量,原列表不受影响 print(items) # 输出仍为: [{'value': 2}, {'value': 4}]
内容的提问来源于stack exchange,提问作者Reham Ashraf
相关产品推荐
相关产品推荐

