Change list entries based on condition in python

Question:

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"
     
Asked By: Hackerman

||

Answers:

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)
Answered By: funnydman
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.