Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: why the code for swapping the largest and the smallest numbers isn't working?

Tags:

python

list

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?

like image 803
Maxim Nikolsky Avatar asked Feb 24 '26 04:02

Maxim Nikolsky


2 Answers

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.

like image 59
Stefan Pochmann Avatar answered Feb 25 '26 19:02

Stefan Pochmann


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)

like image 24
Dmitry.Samborskyi Avatar answered Feb 25 '26 17:02

Dmitry.Samborskyi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!