Kshitij Agarwal
Kshitij Agarwal

Reputation: 3410

How to fix the multiple value assignment to the variables in the python code below?

Given a list of unique numbers in python, I need to swap the positions of the maximum and minimum numbers in the list.

Apart from the traditional way of doing by getting the positions of the numbers by for loop, I tried to do that by the in-built python functions and used it directly in the multiple variables assignment method which is shown below.

a = [i for i in range(6, 1, -1)]
print("The original array is =", a)  # print's [6, 5, 4, 3, 2]

index_max = a.index(max(a))
index_min = a.index(min(a))

# a[ a.index(max(a)) ], a[ a.index(min(a)) ] = min(a), max(a)  #print's [6, 5, 4, 3, 2]
a[index_max], a[index_min] = min(a), max(a)  # print's [2, 5, 4, 3, 6]

print("The swapped array is =", a)

Line no.7 doesn't work as it gives the output [6, 5, 4, 3, 2], instead of [2, 5, 4, 3, 6].

Whereas line no.8 works perfectly!!

Upvotes: 2

Views: 148

Answers (2)

enzo
enzo

Reputation: 11496

According to docummentation of Python:

WARNING: Although the definition of assignment implies that overlaps between the left-hand side and the right- hand side are `safe' (e.g., "a, b = b, a" swaps two variables), overlaps within the collection of assigned-to variables are not safe! For instance, the following program prints "[0, 2]":

x = [0, 1]
i = 0
i, x[i] = 1, 2
print x

So the problem is that, in line 7, Python first does

a [a.index(max(a))] = min(a)

Now, a = [2, 5, 4, 3, 2]. After that, Python does

a [a.index(min(a))] = max(a)

But min(a) = 2, and a.index(2) returns 0. So, in the end, a = [6, 5, 4, 3, 2]. That's why assign the index of min and max before swap the variables does work.

Reference: https://docs.python.org/2.0/ref/assignment.html


Edit: reference to Python 3 as suggested by @chepner:

Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are ‘simultaneous’ (for example a, b = b, a swaps two variables), overlaps within the collection of assigned-to variables occur left-to-right, sometimes resulting in confusion. For instance, the following program prints [0, 2]:

x = [0, 1]
i = 0
i, x[i] = 1, 2   # i is updated, then x[i] is updated
print(x)

Reference: https://docs.python.org/3/reference/simple_stmts.html#assignment-statements

Upvotes: 2

olinox14
olinox14

Reputation: 6653

The important here is the order of the operations. When you do:

a[ a.index(max(a)) ], a[ a.index(min(a)) ] = min(a), max(a)

Python do things in that order:

  • max(a) # >> 6
  • a.index(max(a)) # >> 0
  • a[...] = min(a) # >> a[0] = 2

Then, it do the same with the second member:

  • min(a) # >> 2
  • a.index(min(a)) # >> 0
  • a[...] = max(a) # >> a[0] = 6

The bad behaviour is natural, since you changed the index during the operation...

Upvotes: 1

Related Questions