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

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

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

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值