user13451259
user13451259

Reputation:

python using random.shuffle() on only part of a list

I am trying to implement a genetic algorithm in python. I have a list of 100 objects, sorted, and I need to access the top 30 plus 20 random others. My method is:

random.shuffle(list[30:])  #keep top 30, shuffle the rest
for x in range (50):
    list[x].do_stuff

This doesn't work, the list is unchanged. Is my syntax wrong or is my entire method impossible? thanks

Upvotes: 0

Views: 730

Answers (1)

Ibrahim
Ibrahim

Reputation: 844

you probably want to do this

your_sliced_list = a[30:]
random.shuffle(your_sliced_list)
a[30:] = your_sliced_list

list is a python builtin so you shouldn't use it as a variable name as it overwrites the builtin, thats why in the code I have used a instead of list.

The reason why your code wasn't working was that when you slice the list it creates a new list which isn't assigned to a variable and random.shuffle shuffles that.

Upvotes: 1

Related Questions