jbssm
jbssm

Reputation: 7151

Exchange position of 2 array elements in Python

Is there any easy way to exchange the position of 2 elements - or better yet, n elements - in an array?

I came up with some code, but it looks quite ugly and the performance should be a bit bad:

chromo = [[1,2], [3,4], [5,6]]

gene1Pos = random.randrange(0, len(chromo)-1, 1)
gene2Pos = random.randrange(0, len(chromo)-1, 1)
tmpGene1 = chromo[gene1Pos]
tmpGene2 = chromo[gene2Pos]
chromo[gene1Pos] = tmpGene2
chromo[gene2Pos] = tmpGene1

This should work, but well, it's not nice. The better way would be a routine like random.shuffle but that instead of mixing everything would mix just a number n of elements. Do you have any idea?

Upvotes: 0

Views: 450

Answers (3)

louis.luo
louis.luo

Reputation: 2971

try

>>> chromo[gene1Pos], chromo[gene2Pos] = chromo[gene2Pos], chromo[gene1Pos]

So you just need to make sure you have the right genXPos

Upvotes: 6

dkamins
dkamins

Reputation: 21918

There's nothing wrong with what you're doing. You can simplify it by removing one of the temp variables though. To swap a and b, all you need is this:

tmp = a
a = b
b = tmp

Upvotes: -1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798546

Just combine the normal mechanism for swapping variables in Python with slicing/slice assignment.

>>> a = [1, 2, 3, 4, 5]
>>> a[2:3], a[4:5] = a[4:5], a[2:3]
>>> a
[1, 2, 5, 4, 3]

Upvotes: 1

Related Questions