(Yet Another) List Aliasing Conundrum

前端 未结 6 710
忘掉有多难
忘掉有多难 2020-12-10 18:37

I thought I had the whole list alias thing figured out, but then I came across this:

    l = [1, 2, 3, 4]
    for i in l:
        i = 0
    print(l)
<         


        
6条回答
  •  天命终不由人
    2020-12-10 18:45

    When you say i = 0 you assign a new value to the variable i.

    When you say i[0] = 0 you modify the list in variable i, setting the first element to a new value. Since the list in i is an element of l, l ends up with modified elements.

提交回复
热议问题