2

I am making a hangman game in Python, and I understand how to randomly select an item from a list, but I was wondering if there was a way to randomly select the list in general.

For example, I have two lists, list1 and list2 Is there a way to randomly select between list1 and list2, and then randomly select a word from the randomly selected list.

I hope that makes sense

2
  • 1
    make a list that contains both other lists and random.choice() that list Commented Dec 19, 2018 at 19:06
  • it is the same as selecting a random element from a list, only the lists are your elements! Commented Dec 19, 2018 at 19:06

4 Answers 4

6

You could use random.choice twice:

import random first = ['one', 'word'] second = ['two', 'more', 'and'] selected = random.choice(random.choice([first, second])) print(selected) 

Output

word 
Sign up to request clarification or add additional context in comments.

Comments

2
import random # Create a list of your lists list_of_lists = [lists1, list2, list3] # Select a random list from your list of lists random_list = random.choice(list_of_lists) # Select a random word from the randomly selected list random_word = random.choice(random_list) 

Comments

0

You can use random.choice to select a random list, and then use random.choice again to select a value from that list:

import random list1 = ['1','2','3'] list2 = ['4','5','6'] word = random.choice(random.choice([list1, list2])) 

Comments

0

The two list case if covered by other answers.

If you have an arbitrarily nested, possibly irregular list (or sequence), you can write a recursive function.

from collections import Sequence import random def go_deeper(x): return (isinstance(x, Sequence) and not isinstance(x, (str, bytes))) # and other sequence types you wish to exclude def select(candidate): if go_deeper(candidate): return select(random.choice(candidate)) return candidate 

Demo:

>>> l = ['foo', 'bar'] >>> select(l) 'bar' >>> >>> l = [[[(0,)]]] >>> select(l) 0 >>> >>> l = [1, 2, [3, 4, [5]], [[6, [7, 8]], 9]] >>> select(l) 9 >>> select(l) 1 >>> select(l) 2 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.