Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange inline assignment

I'm struggling with this strange behaviour in Python (2 and 3):

>>> a = [1, 2]
>>> a[a.index(1)], a[a.index(2)] = 2, 1

This results in:

>>> a
[1, 2]

But if you write

>>> a = [1, 2]
>>> a[a.index(1)], a[a.index(2)] = x, y

where x, y != 2, 1 (can be 1, 1, 2, 2 , 3, 5, etc.), this results in:

>>> a == [x, y]
True

As one would expect. Why doesn't a[a.index(1)], a[a.index(2)] = 2, 1 produce the result a == [2, 1]?

>>> a == [2, 1]
False
like image 686
Dargor Avatar asked Nov 03 '15 13:11

Dargor


People also ask

What is inline assignment?

Inline Assignment Grading provides a way to grade assignments within your Blackboard course. Instead of needing to download student files for viewing, instructors are able to view these files “inline,” i.e. in the web browser, without the need for plug-ins or additional software.

Does Python support inline assignment?

Python doesn't support Inline assignment.


1 Answers

Because it actually gets interpreted like this:

>>> a = [1, 2]
>>> a
[1, 2]
>>> a[a.index(1)] = 2
>>> a
[2, 2]
>>> a[a.index(2)] = 1
>>> a
[1, 2]

To quote, per the standard rules for assignment (emphasis mine):

  • If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

The assignment to a[a.index(1)] (i.e. a[0]) happens before the second assignment asks for a.index(2), by which time a.index(2) == 0.

You will see the same behaviour for any assignment:

foo = [a, b]
foo[foo.index(a)], foo[foo.index(b)] = x, y

where x == b (in this case, any assignment where the first value on the right-hand side is 2).

like image 148
jonrsharpe Avatar answered Sep 28 '22 05:09

jonrsharpe