Reputation: 23
I am trying to swap two elements in a list, but maybe I'm doing it wrong! It doesn't swap elements.
f= [4,3,1,2]
f[0],f[f.index(min(f[2:]))] = f[f.index(min(f[2:]))] ,f[0]
print(f)
[4, 3, 1, 2]
Upvotes: 0
Views: 45
Reputation: 449
ind = f[2:].index(min(f[2:])) + 2
f[ind], f[0] = f[0], f[ind]
However, this code seems quite uneffective as you have, at worst, to parse f
two times (one to find the minimum and one to find its index
, so I would recommand doing this with a for
loop, or using numpy.argmin
if you already use numpy
in your project.
ind = 2
minim = f[2]
for i,t in enumerate(f[3:]):
if t < minim:
ind = i + 3
minim = t
f[0], f[ind] = minim, f[0]
Upvotes: 1
Reputation: 554
var1cpy = f[f.index(min(f[2:]))]
f[f.index(min(f[2:]))] = f[0]
f[0] = var1cpy
It worked for me
Upvotes: 0