您的位置:首页 > 编程语言 > Python开发

Python, difference between two ways for removing last elem of list

2015-08-30 12:42 549 查看
For immutable variable, python is pass-by-value. Actually, python will create a new instance for immutable variable. But for mutable variable, python is pass-by-reference.

I found list = list[0:-1], python will create a new sublist, but for list.pop(), it will not.

Here is an example.

Example 1

[code]a = [1,2,3]
print id(a)

def func(lst):
    print id(lst)
    lst = lst[0:-1]
    pritn lst, id(lst)

func(a)
print a, id(a)


The output is

[code]4147851564
4147851564
[1, 2] 4147852172
[1, 2, 3] 4147851564


In this example, id() function is used to identify object. It is an integer which is guaranteed to be unique and constant for this object. We could think of it as the memory address.

We can find, in this example, the lst = lst[0:-1] give rise to the change of address of lst. The original list a is not affected.

Example 2

[code]a = [1,2,3]
print id(a)

def func(lst):
    print id(lst)
    lst.pop()
    print lst, id(lst)

func(a)
print a, id(a)


Output is

[code]4147933484
4147933484
[1, 2] 4147933484
[1, 2] 4147933484


We notice that, for list.pop(), python will not alter the address of list.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: