when a python list iteration is and is not a reference

后端 未结 3 719
野的像风
野的像风 2021-01-14 04:07

Could someone please offer a concise explanation for the difference between these two Python operations in terms of modifying the list?

demo = [\"a\", \"b\",         


        
3条回答
  •  孤街浪徒
    2021-01-14 04:20

    The loop variable d is always a reference to an element of the iterable object. The question is not really a matter of when or when isn't it a reference. It is about the assignment operation that you are performing with the loop.

    In the first example, you are rebinding the original reference of an element in the object, with another reference to an empty string. This means you don't actually do anything to the value. You just assign a new reference to the symbol.

    In the second example, you are performing an indexing operation and assigning a new reference to the value at that index. demo remains the same reference, and you are replacing a value in the container.
    The assignment is really the equivalent of: demo.__setitem__(c, "")

    a = 'foo'
    id(a)  # 4313267976
    a = 'bar'
    id(a)  # 4313268016
    
    l = ['foo']
    id(l)  # 4328132552
    l[0] = 'bar'
    id(l)  # 4328132552
    

    Notice how in the first example, the object id has changed. It is a reference to a new object. In the second one, we index into the list and replace a value in the container, yet the list remains the same object.

提交回复
热议问题