Chidananda Nayak
Chidananda Nayak

Reputation: 23

swaping of two elements in a pythonic list

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

Answers (2)

globglogabgalab
globglogabgalab

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

Adept
Adept

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

Related Questions