• 首页
• Python
• 再次使用该值作为索引以避免局部变量时，列表交换两个元素失败

# 再次使用该值作为索引以避免局部变量时，列表交换两个元素失败 [英] list swap two elements failed when using the value as index again to avoid a local variable

### 问题描述

``````l1=[0,2,1]
index=1
from ipdb import set_trace; set_trace()
l1[index], l1[l1[index]] = l1[l1[index]], l1[index]
print(l1)
``````

### 推荐答案

``````l1=[0,2,1]
index=1
l1[l1[index]], l1[index] = l1[index], l1[l1[index]]
print(l1)
``````

``````[0, 1, 2]
``````

``````import dis
def switch():
l1=[0,2,1]
index=1
l1[index], l1[l1[index]] = l1[l1[index]], l1[index]
return l1
dis.dis(switch)
6 BUILD_LIST               3
8 STORE_FAST               0 (l1)

12 STORE_FAST               1 (index)

20 BINARY_SUBSCR
22 BINARY_SUBSCR
28 BINARY_SUBSCR
30 ROT_TWO
36 STORE_SUBSCR
44 BINARY_SUBSCR
46 STORE_SUBSCR

50 RETURN_VALUE
``````

``````l1[index], l1[l1[index]] = l1[l1[index]], l1[index]

after stack swapping == 1, 2

l1[1] == 1
l1[1] == 2
# So you have modified only index 1, and then overwritten it with its original value.
``````

``````             14 LOAD_FAST                0 (l1)           ¯¯|
16 LOAD_FAST                0 (l1)   ¯¯|  2    | 1 ---------->
18 LOAD_FAST                1 (index)__|     __|              ↓
20 BINARY_SUBSCR                                              |
22 BINARY_SUBSCR                                              |
24 LOAD_FAST                0 (l1)   ¯¯|  2 ------------------------>
26 LOAD_FAST                1 (index)__|                      |       ↓
28 BINARY_SUBSCR                                              |       |
30 ROT_TWO                                                    |       |
32 LOAD_FAST                0 (l1)   ¯¯|                      ↓       |
34 LOAD_FAST                1 (index)__|  l1[1] = 1  <--------        |
36 STORE_SUBSCR                                   |                   |
38 LOAD_FAST                0 (l1)                |  ¯¯|              |
40 LOAD_FAST                0 (l1)   ¯¯|          ↓    |              |
42 LOAD_FAST                1 (index)__| l1[1] == 1  __| l1[1] = 2 <---
44 BINARY_SUBSCR
46 STORE_SUBSCR
``````

``````l1[l1[index]], l1[index] = l1[index], l1[l1[index]]

after stack swapping == 2, 1

l1[2] = 2
l1[1] = 1
# Here, as you have not changed the value of `l1[index]` in the first assignment, the order remains.
``````

``````l1 = [0, 1, 2]

l1[index], l1[l1[index]] = l1[l1[index]], l1[index]

after stack swapping == 1, 1

l1[1] == 1
l1[1] == 1
------------------------------------------------------------------
l1[l1[index]], l1[index] = l1[index], l1[l1[index]]

after stack swapping == 1, 1

l1[1] = 1
l1[1] = 1
# Here both have same value, so it does not modify.
``````

``````l1 = [0, 2, 1]
index1 = 1
index2 = l1[index1]
l1[index1], l1[index2] = l1[index2], l1[index1]
print(l1)
# [0, 1, 2]
``````