Python list問題

  1. l1 = [5, 6]
  2. l2 = [7, 8, l1]
  3. l1 = [2, 3]
  4. print(l2)
複製代碼

上面段code點解係輸出[7, 8, [5, 6]],而吾係[7, 8, [2, 3]]?
下面段code就得
  1. l1 = [5, 6]
  2. l2 = [7, 8, l1]
  3. l1[0] = 2
  4. l1[1] = 3
  5. print(l2)
複製代碼



Thanks
PS: Python新手

I guess at line 03, l1 = [2, 3], l1 is pointing to a new List already (very bad variable name btw, hard to read), but it doesn't change l2[2] (which still points to the old List[5,6]. making l2[2] the only way to access [5,6].

TOP

I guess at line 03, l1 = [2, 3], l1 is pointing to a new List already (very bad variable name btw, h ...
CVSDF 發表於 2019-10-21 20:11

正解,
另外樓主可以上呢個網試吓你段code,睇吓每一行code執行的情況。
http://www.pythontutor.com/visualize.html#mode=edit

TOP

thanks

TOP

老餅唔識Python,應該係
pass by reference
pass by value
嘅分別

TOP