How does this chain assignment work?

前端 未结 3 1368
北海茫月
北海茫月 2021-01-20 03:57

Consider the following code; it is a bad programming practice. I am wondering why the resulting list A is [1, 1, 3] rather than [1, 2, 1]

3条回答
  •  走了就别回头了
    2021-01-20 04:46

    On line 3 you have a chained assignment

    t = A[t] = A.count(3)
    

    t = A.count(3) is evaluated first – t set to the return value of A.count(3) which in this case is 1. Then the member of A at index t(=1) is set to the return value of A.count(3), which is still 1.

    Read more about chained assignments in Python here

提交回复
热议问题