Luc Luc - 1 year ago 68
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

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

Size=["Extra Large","Large","Medium","Small","Tiny"]
while len(Tree)<len(Leaves)*len(Trunk)*len(Size):
if Tree != NewCombination:


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

Answer Source

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)"]
NewCombination = []

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

    if Tree != NewCombination:

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download