Yilion
Yilion

Reputation: 19

How to select random element from a list in python

I forgot how to pick a random color from the list that I made of the colors. Here's the code I have right now.

from turtle import *
from random import *

speed(0)
bgcolor=('black')
colors=('purple', 'teal', 'blue', 'magenta', 'lilac', 'cyan')
for i in range(15):
    draw:(circle)

Upvotes: 0

Views: 1120

Answers (2)

N. Arunoprayoch
N. Arunoprayoch

Reputation: 942

By using random.choice() also should be considered

import random

colors = ('purple', 'teal', 'blue', 'magenta', 'lilac', 'cyan')
selected_color = random.choice(colors)

Result

selected_color
# 'cyan'

Upvotes: 2

Jay
Jay

Reputation: 2946

You can use:

colour = colors[random.randint(0, len(colours)-1)]

This will pick a random item from your list

Upvotes: 0

Related Questions