Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this chain assignment work? [duplicate]

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]. From the view of Java, the result should be [1, 2, 1]. Can anyone explain why this result is what it is?

A = [1, 2, 3]
t = 2
t = A[t] = A.count(3)

After evaluation, A is [1, 1, 3] and t is 1.

My Python version is 3.3.

like image 905
hiway Avatar asked Jan 19 '26 11:01

hiway


1 Answers

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

like image 196
Henrik Avatar answered Jan 22 '26 02:01

Henrik