Imagine we have a list of numbers a
where all numbers are different, and we want to swap the largest one and the smallest one. The question is, why this code in Python:
a[a.index(min(a))], a[a.index(max(a))] = a[a.index(max(a))], a[a.index(min(a))]
isn't working?
Why does it fail? Let's take a = [1, 2, 3, 4]
as example.
First, the right side is evaluated:
a[a.index(max(a))], a[a.index(min(a))] => 4, 1
That's btw of course the same as
max(a), min(a) => 4, 1
Next, the assignments happen, from left to right:
First, setting a[a.index(min(a))]
to 4 makes the list [4, 2, 3, 4]
, as the minimum is at the front.
Then, setting a[a.index(max(a))]
to 1 makes the list [1, 2, 3, 4]
again, as the maximum has been written at the front, so that's where it is found now and where the 1 gets written.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments