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

Maxim Nikolsky

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?

Stefan Pochmann

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.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Python: Why isn't this working?

From Dev

Why isn't this code working without an else block to the if statement? - Python

From Dev

Why isn't my Python 3 code working?

From Dev

Why jQuery code isn't working?

From Dev

Approximating Pi - Why isn't this code working?

From Dev

Why isn't selectedIndex working in this code?

From Dev

Why isn't my pagination code working?

From Dev

why isn't this login form code working?

From Java

Code isn't swapping cases as I expect it to

From Dev

Why isn't this Python JDBC connection working?

From Dev

Why isn't & working?

From Dev

Why isn't < working to read in a file from the command line (simple Python code)?

From Dev

Why isn't this pandas Boolean indexing code on numeric columns working?

From Dev

Why isn't my INSERT IGNORE code NOT working?

From Dev

Why isn't my code to fill a dictionary(and tableview) working?

From Dev

Why isn't my binary to English code working?

From Dev

Node.js - Why isn't this code working?

From Dev

Why isn't this SFML C++ code working ?

From Dev

Why isn't my binary to English code working?

From Dev

Why isn't this code working? (on my iphone 6, chrome)

From Dev

Why isn't my user alert code in Swift working as intended

From Dev

Why isn't console.log working in the following Express code?

From Dev

Why isn't my reversing MIPS code working correctly?

From Dev

R largest/smallest representable numbers

From Dev

R largest/smallest representable numbers

From Dev

Find largest and smallest numbers in an array

From Dev

why this for()loop isn't working?

From Dev

Why this snippet isn't working?

From Dev

Why isn't 'source' working?

Related Related

HotTag

Archive