when a python list iteration is and is not a reference

后端 未结 3 717
野的像风
野的像风 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:22

    In the first example, the variable d can be thought of a copy of the elements inside the list. When doing d = "", you're essentially modifying a copy of whatever's inside the list, which naturally won't change the list.

    In the second example, by doing range(len(demo)) and indexing the elements inside the list, you're able to directly access and change the elements inside the list. Therefore, doing demo[c] would modify the list.

    If you do want to directly modify a Python list from inside a loop, you could either make a copy out the list and operate on that, or, preferably, use a list comprehension.

    So:

    >>> demo = ["a", "b", "c"]
    >>> test = ["" for item in demo]
    >>> print test
    ["", "", ""]
    
    >>> demo2 = [1, 5, 2, 4]
    >>> test = [item for item in demo if item > 3]
    >>> print test
    [5, 4]
    

提交回复
热议问题