Home > Blockchain >  Change list entries based on condition in python
Change list entries based on condition in python

Time:08-10

I want to "draw a picture": I create a list with entries of o´s. Then I want to go through each element of the list to weigh a random number against a previously chosen 'density' number. If the number is smaller than my previously chosen density, then I want that entry to be replaced by a T.. Then it's the next element's turn with a new random number.

This is my code so far: It either gives all o's or just a single T.

import random

list = []
number_of_entries = 5
density = 0.5

list.append(["o"]*number_of_entries)  # ['o', 'o', 'o', 'o', 'o']

for index, entry in enumerate(list):
    if random.random() < density:    
        list[index] = "X"
     

CodePudding user response:

Your variable list (by the way don't use reserved words as variables names) has two nested lists and that's the problem, try this:

import random

number_of_entries = 5
density = 0.5
alist = ["o"] * number_of_entries
for index, entry in enumerate(alist):
    if random.random() < density:
        alist[index] = "X"
        
print(alist)
  • Related