交换列表里两个数的位置python_Python交换列表

In python, when I assign a list to another, like:

a = [1,2,3]

b = a

Now b and a point to the same list. Now considering two lists,

a = [1,2,3]

b = [4,5,6]

a,b = b,a

Now how is it that they are swapped like any other data type and does not end up both pointing to the same list?

解决方案

Looks like Python internally swaps the items. Check this program

a, b = [1, 2], [2, 3]

def func():

a, b = b, a

import dis

dis.dis(func)

Output

4 0 LOAD_FAST 0 (b)

3 LOAD_FAST 1 (a)

6 ROT_TWO

7 STORE_FAST 1 (a)

10 STORE_FAST 0 (b)

13 LOAD_CONST 0 (None)

16 RETURN_VALUE

So, Python pushes references from b and a in the stack with LOAD_FAST. So, now the top most element is the reference pointed by a and the next one is the reference pointed by b. Then it uses ROT_TWO to swap the top two elements of the stack. So, now, the top most element is the reference pointed by b and the next one is the reference pointed by a and then assigns the top two elements of the stack to a and b respectively with STORE_FAST.

That's how sorting is happening in the assignment statement, when the number of items we deal with is lesser than 4.

If the number of items is greater than or equal to four, it builds a tuple and unpacks the values. Check this program

a, b, c, d = [1, 2], [2, 3], [4, 5], [5, 6]

def func():

a, b, c, d = d, c, b, a

import dis

dis.dis(func)

Output

4 0 LOAD_FAST 0 (d)

3 LOAD_FAST 1 (c)

6 LOAD_FAST 2 (b)

9 LOAD_FAST 3 (a)

12 BUILD_TUPLE 4

15 UNPACK_SEQUENCE 4

18 STORE_FAST 3 (a)

21 STORE_FAST 2 (b)

24 STORE_FAST 1 (c)

27 STORE_FAST 0 (d)

30 LOAD_CONST 0 (None)

33 RETURN_VALUE

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值