为什么python中的列表操作在功能范围之外运行? [英] Why do list operations in python operate outside of the function scope?

查看:106
本文介绍了为什么python中的列表操作在功能范围之外运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的python代码中,将变量number传递给函数addone,并对本地副本进行操作.数字的值保持不变.

In the python code below, variable number is passed to the function addone, and a local copy is operated on. The value of number stays the same.

def addone(num):
    num = num + 1
    print "function: added 1, now %d" % num

number = 5
print "Before:", number
addone(number)
print "After:", number

输出:

Before: 5
function: added 1, now 6
After: 5

但是,其行为似乎与列表操作(如pop,append等)不同.这使我有些困惑.所有列表操作是否都在全球范围内运作?如果是这样,那么背后有什么特殊的原因吗?

However, the behavior appears to be different with list operations like pop, append etc. This somewhat confuses me. Do all list operations operate globally ? If so, is there any particular reason behind it ?

def pop_first(stuff):
    popped = stuff.pop(0)
    print "function: '%s' was popped!" % popped

words = ["A", "list", "of", "words"]
print "Before:", words
pop_first(words)
print "After:", words

输出:

Before: ['A', 'list', 'of', 'words']
function: 'A' was popped!
After: ['list', 'of', 'words']

推荐答案

简短的答案是因为列表是可变的而整数是不可变的.

The short answer is because lists are mutable and integers are immutable.

您不能在适当的地方对整数进行突变,因此我们将其称为不可变的".考虑到这一点,诸如在整数上加法之类的操作不会修改原始对象,而是返回一个新值-因此您的原始变量将保持不变.因此,如果我们存储对整数的引用,则只要我们不更改其中任何一个,它们就只会是同一对象:

You cannot mutate an integer in place, so we call it 'immutable'. With this in mind, things like addition on an integer do not modify the original object, but rather return a new value- so your original variable will remain the same. Therefore, if we store a reference to an integer, they will only be the same object as long as we have not changed either one of them:

>>> foo = 1
>>> bar = foo
>>> foo is bar
True
>>> foo += 2
3
>>> foo
3
>>> bar
1
>>> foo is bar
False


另一方面,列表是可变的"(可以修改相同的对象引用),并且诸如pop()之类的操作会原位更改list,从而更改原始内容.这也意味着,如果您编辑对诸如list之类的可变对象的引用,原始对象也将被更改:


On the other hand lists are 'mutable' (can modify that same object reference), and operations like pop() mutate the list in-place, changing the original. This also means that if you edit a reference to a mutable object such as a list, the original will be changed as well:

>>> baz = [1, 2, 3, 4, 5]
>>> qux = baz
>>> qux is baz
True
>>> baz.pop()
5
>>> qux
[1, 2, 3, 4]
>>> baz
[1, 2, 3, 4]
>>> qux is baz
True

这篇关于为什么python中的列表操作在功能范围之外运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆