Question: I am working on a genetic algorithm, defined a class:

```
class Solution:
    def __init__(self, N=1, K=1):
        self.wi = {}
        self.loss = 0
        id = random.sample([i for i in range(N)], K)
        wi = [random.random() for _ in range(K)]
        for i in range(K):
            self.wi[id[i]] = wi[i]

```

Generated a list of obj

```
population = [Solution(N, K) for _ in range(100)]

```

In my algorithm a new obj `C` will be created from the `population` list, and replace the obj in the `population` with the largest `loss`

I tried

```
largest = max(population, key = attrgetter('loss'))
largest = C

```

But the obj in the list do not change with `largest`, what can I do to make that happen?

Answer: 
Instead of calculating the maximum object, you can calculate the maximum index, and then set population for that index:

```
largest**\_i** = max(**range(len(population))**,key=**lambda i:population[i]**.loss)
```

and then set:

```
population[largest_i] = C

```

this will only scan the list once.
Replace

```
from operator import attrgetter

largest = max(population, key = attrgetter('loss'))
largest = C

```

with

```
largest = max(population, key = attrgetter('loss'))
population[population.index(largest)] = C

```