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.
Better to get index of max and min first:
i_min, i_max = a.index(min(a)), a.index(max(a))
a[i_min], a[i_max] = a[i_max], a[i_min]
Other way result can be unpredictable)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With