List vs. int assignment - “Every variable is a pointer”

前端 未结 1 772
旧巷少年郎
旧巷少年郎 2021-01-21 02:19

I know it\'s a very basic question, but I need help understanding this short concept.

I\'m studying Python, and the book says \"Every variable in Python is a pointer to

相关标签:
1条回答
  • 2021-01-21 02:32

    Your first example can be explained as follows:

    x=[1,2,3]  # The name x is assigned to the list object [1,2,3]
    y=x        # The name y is assigned to the same list object referenced by x
    x[1]=3     # This *modifies* the list object referenced by both x and y
    print y    # The modified list object is printed
    

    The second example however only reassigns the name x to a different integer object:

    x=5      # The name x is assigned to the integer object 5
    y=x      # The name y is assigned to the same integer object referenced by x
    x=7      # The name x is *reassigned* to the new integer object 7
    print y  # This prints 5 because the value of y was never changed
    

    Here is a reference on assignment in Python.

    0 讨论(0)
提交回复
热议问题