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

来源:互联网 发布:淘宝摄影技巧 编辑:程序博客网 时间:2024/05/16 19:46

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

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

41478515644147851564[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

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

41479334844147933484[1, 2] 4147933484[1, 2] 4147933484

We notice that, for list.pop(), python will not alter the address of list.

0 0