Ad

Randomly Change/mutate One Value In A List

- 1 answer

I'm writing a genetic algorithm and want to randomly mutate a number within a list.

If I had a list, for example:

[1,2,3,4,5]

How could I take the list and change just one of the numbers to a random number, for example:

[1,2,7,4,5]

or

[1,3,3,4,5]
Ad

Answer

Use random.randint:

l=[1,2,3,4,5]
import random
l[random.randint(0,len(l)-1)]=random.randint(min(l),max(l)-1)

And now:

print(l)

Is (every time it's different, this is just a first-time-output):

[1, 4, 3, 4, 5]
Ad
source: stackoverflow.com
Ad