user6137931 user6137931 - 7 months ago 14
Python Question

How to randomly replace a string in a list

If I have something like this:

L = ['-','-','-','-','-','-','-']


And let's say that I want to replace certain number of those strings. How do I randomly select a position within the list to replace it for something else? For example:

L = ['-','*','-','-','-','*','*']

Answer

Use random.randrange

    import random

some_list=["-","-","-","-","-","-","-"]

n=2
for i in range(n):
    some_list[random.randrange(0,len(some_list))]="*"