Kushagra Gupta
Kushagra Gupta

Reputation: 614

How to select a random element from a part of a list?

I have a list called game

game = ['X','O',' ',' ',' ',' ',' ',' ',' ']

I need to select a random element from all the ' ' elements only. It will then change it to X or O and do again. Using simple random.choice() has a chance of never ending. random.choices() returns the element instead of its index so I cannot think of a way to update the weights.

Upvotes: 0

Views: 76

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 61063

Determine which indices have spaces and use random.choice to choose one

from random import choice

game = ['X','O',' ',' ',' ',' ',' ',' ',' ']
index = choice([i for i, x in enumerate(game) if x == ' '])

Upvotes: 2

Related Questions