Luc Luc - 4 months ago 6
Python Question

How to randomly choose a string from a list, and insert it into a new one?

I've recently made this program to simulate the concept of random generation with my example being trees, however I don't understand why I can't find an element within the list with a randomly generated number. I tried

Leaves.index()
but It doesn't seem to be working. Are there any ways to randomly take a string from one of my lists and add it into another list?

import random

Leaves=["Pointy","Rounded","Maple","Pine","Sticks"]
Trunk=["Oak","Birch","Maple","Ash","Beech","Spruce"]
Size=["Extra Large","Large","Medium","Small","Tiny"]
Tree=[]
while len(Tree)<len(Leaves)*len(Trunk)*len(Size):
NewCombination=Leaves.index(random.randrange(len(Leaves)))+Trunk.index(random.randrange(len(Trunk)))+Size.index(random.randrange(len(Size)))
if Tree != NewCombination:
Tree=Tree+NewCombination
print(Tree)


Error:

Traceback (most recent call last):
File "C:/Users/invis_000/Documents/Coding/Python/Generation.py", line 8, in <module>

Answer

From what I can tell, it seems like you want to create a list of a bunch of random features. The way I would personally go about this is by using the random method Choice

Choice allows us to pick a string from a list, then we use a function called .append that lets us include it in another list

from random import choice

Leaves=["(Pointy ","(Rounded ","(Maple ","(Pine ","(Sticks "]
Trunk=["Oak ","Birch ","Maple ","Ash ","Beech ","Spruce "]
Size=["Extra Large)","Large)","Medium)","Small)","Tiny)"]
Tree=[]
NewCombination = []

while len(Tree)<len(Leaves)*len(Trunk)*len(Size):
    NewCombination.append((choice(Leaves)) + (choice(Trunk) + (choice(Size))))

    if Tree != NewCombination:
        Tree=Tree+NewCombination
print(Tree)

I have also made it much easier to see the printed list by including brackets and spaces in your original three lists

Comments