user10608627
user10608627

Reputation:

Randomly change/mutate one value in a list

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]

Upvotes: 0

Views: 4001

Answers (4)

Mimi
Mimi

Reputation: 95

Different approach to similar problem, I hope it will helps with different point of view :)

As long as I have list of e.g. mixed string elements I use enumerate and some random choice function (in my case from Numpy). e.g. when I have list of different atoms, from which I want to randomly choose one atom of only one type, I can wrote:

import numpy as np

mixed_atm_list = ["Pb", "C", "H", "Pb", "C", "C", "Sn", "H"]
random_choice_atm = "C"

find_idx = [idx for idx, atm in enumerate(mixed_atm_list) if atm == random_choice_atm]

randomly_selected_carbon_atom = np.random.choice(find_idx)
randomly_selected_carbon_atom = mixed_atm_list[randomly_selected_carbon_atom]

Upvotes: 0

fferri
fferri

Reputation: 18940

Use random.randrange and random.randint:

>>> import random
>>> index = random.randrange(len(mylist))
>>> mylist[index] = random.randint(minVal, maxVal)

 

Edit: if you want to always make a change (i.e. never leave the list unchanged), consider incrementing the item by a non-zero value:

>>> mylist[index] += random.choice([1, -1]) * random.randint(1, maxChange)

Upvotes: 3

Bharat Jogdand
Bharat Jogdand

Reputation: 438

Use random.randint:

import random
temp_list = [1,2,3,4,5]
temp_list[index_of_list] = random.randint(minValue, maxValue)

or you can try like:

temp_list[random.randint(0, (len(temp_list))-1)] = random.randint(minValue, maxValue)

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71580

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]

Upvotes: 1

Related Questions