why the next python line is not a syntax error? If it is really not then how can I use it and in which situation it will be useful?
a= range(10)[1:3]=[2,3]
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Python supports multiple assignments on the same line:
Since you are assigning a first to a list(a mutable object in python) and then assigning both part of that list(which is mutable) and a to the contents of a third item, python is ok with it. If you had replaced your middle value with something that wasn’t mutable, you would get an error.
Interestingly, a line like this still throws an error, because you are attempting to assign the values 3 and 4 to the literal values 1 and 2.
While this does not:
The key in this case is that by using slice notation you are assigning to the range inside of the list, instead of reassigning to the literal values in the list.
Additionally, the lines
and
Are valid, the first one because the inner lists and dicts are both mutable and iterable, and the second one because you are assigning 3, and 4 to the variables b and c instead of literals(thanks Sven :D).
Edit To answer the op’s final question.
This just comes down to the final(right-most) assignment of b, a = a, b. Observe:
It’s confusing, but the way I interpret this is that a and b are not re-evaluated / assigned new values until the statement is finished, so the assignment that matters is the one farthest to the right. If the last statement is a, b = a, b or b, a = b, a, a and b’s values don’t change. If it is a, b = b, a or b, a = a, b, the values are switched.