from random import choice

choice(your_list)

example:

from random import choice

my_list = ["apples", "oranges", "pears"]
print(choice(my_list)[0])
Answer from James on Stack Overflow
🌐
Quora
quora.com › How-do-you-generate-a-random-word-from-a-list-in-Python
How to generate a random word from a list in Python - Quora
Answer (1 of 3): There is something called choice function in the random module of Python. You can use it the following way. [code]import random word_list = ['apple','banana','cherry','dates','etc'] random.choice(word_list) [/code]This gives you a random word from a list in Python. Also, in Py...
Discussions

Picking a Random Word from a list in python? - Stack Overflow
In Python 3, how would I print a random word from a list of words? More on stackoverflow.com
🌐 stackoverflow.com
Random words generate using python - Stack Overflow
I have a list of words count=100 list = ['apple','orange','mango'] for the count above using random function is it possible to select 40% of the time apple, 30% of the time orange and 30% of ... More on stackoverflow.com
🌐 stackoverflow.com
Random word generator- Python - Stack Overflow
So i'm basically working on a project where the computer takes a word from a list of words and jumbles it up for the user. there's only one problem: I don't want to keep having to write tons of wor... More on stackoverflow.com
🌐 stackoverflow.com
Generating a random word from an array
What is the point of this: for(int i=0;i<10;i++){ y=rand()%4+1; } More on reddit.com
🌐 r/C_Programming
12
0
February 6, 2022
🌐
Quora
quora.com › How-do-you-create-a-random-list-of-words-in-Python
How to create a random list of words in Python - Quora
Answer (1 of 3): t̲h̲i̲s̲ ̲d̲e̲m̲o̲n̲s̲t̲r̲a̲t̲e̲s̲ ̲-̲ ̲A̲l̲ri̲g̲h̲t̲ ̲,̲ ̲t̲o̲ c̲r̲e̲a̲t̲e̲ ̲a̲ ̲r̲a̲nd̲o̲m̲ ̲l̲i̲s̲t̲ ̲of̲ ̲w̲o̲rd̲s̲ ̲i̲n̲ ̲P̲y̲t̲h̲o̲n ̲,̲ ̲y̲o̲u̲’̲l̲l̲ ̲f̲i̲r̲s̲t ̲n̲e̲e̲d̲ ̲a̲ ...
🌐
myCompiler
mycompiler.io › view › 77C7a49UhtZ
RANDOM WORD GENERATOR (Python) - myCompiler
December 29, 2022 - import random import time # Set ... words word_list = ["apple", "book", "desk", "pen", "cat", "dog", "tree", "house", "car", "phone", "computer", "laptop", "keyboard", "mouse", "chair", "table", "door", "window", "wall", "floor"] ...
🌐
EncodedNA
encodedna.com › python › how-to-get-a-random-word-from-a-list-of-words.htm
How to get a Random word from a list of words in Python?
Related article (important) 👉 ... have used in the first example above, is the choice() method. ... The "choice()" method returns a single random element (in our case a word) from a given list (an array)....
Top answer
1 of 2
4

Based on an answer to the question about generating discrete random variables with specified weights, you can use numpy.random.choice to get 20 times faster code than with random.choice:

from numpy.random import choice

sample = choice(['apple','orange','mango'], p=[0.4, 0.3, 0.3], size=1000000)

from collections import Counter
print(Counter(sample))

Outputs:

Counter({'apple': 399778, 'orange': 300317, 'mango': 299905})

Not to mention that it is actually easier than "to build a list in the required proportions and then shuffle it".

Also, shuffle would always produce exactly 40% apples, 30% orange and 30% mango, which is not the same as saying "produce a sample of million fruits according to a discrete probability distribution". The latter is what both choice solutions do (and the bisect too). As can be seen above, there is about 40% apples, etc., when using numpy.

2 of 2
3

The easiest way is to build a list in the required proportions and then shuffle it.

>>> import random
>>> result = ['apple'] * 40 + ['orange'] * 30 + ['mango'] * 30
>>> random.shuffle(result)

Edit for the new requirement that the count is really 1,000,000:

>>> count = 1000000
>>> pool = ['apple'] * 4 + ['orange'] * 3 + ['mango'] * 3
>>> for i in xrange(count):
        print random.choice(pool)

A slower but more general alternative approach is to bisect a cumulative probability distribution:

>>> import bisect
>>> choices = ['apple', 'orange', 'mango']
>>> cum_prob_dist = [0.4, 0.7]
>>> for i in xrange(count):
        print choices[bisect.bisect(cum_prob_dist, random.random())]
🌐
Bobby Hadz
bobbyhadz.com › blog › python-generate-random-word
How to generate random Words or Letters in Python | bobbyhadz
Copied!import random import requests def get_list_of_words(): response = requests.get( 'https://www.mit.edu/~ecprice/wordlist.10000', timeout=10 ) string_of_words = response.content.decode('utf-8') list_of_words = string_of_words.splitlines() return list_of_words words = get_list_of_words() print(words) random_word = random.choice(words) print(random_word) # 👉️ zoo ... If you don't have the requests module installed, install it by running the following command. ... Copied!# 👇️ In a virtual environment or using Python 2 pip install requests # 👇️ For python 3 (could also be pip3.10 depending on your version) pip3 install requests
Find elsewhere
Top answer
1 of 8
122

Reading a local word list

If you're doing this repeatedly, I would download it locally and pull from the local file. *nix users can use /usr/share/dict/words.

Example:

word_file = "/usr/share/dict/words"
WORDS = open(word_file).read().splitlines()

Pulling from a remote dictionary

If you want to pull from a remote dictionary, here are a couple of ways. The requests library makes this really easy (you'll have to pip install requests):

import requests

word_site = "https://www.mit.edu/~ecprice/wordlist.10000"

response = requests.get(word_site)
WORDS = response.content.splitlines()

Alternatively, you can use the built in urllib2.

import urllib2

word_site = "https://www.mit.edu/~ecprice/wordlist.10000"

response = urllib2.urlopen(word_site)
txt = response.read()
WORDS = txt.splitlines()
2 of 8
20

Solution for Python 3

For Python3 the following code grabs the word list from the web and returns a list. Answer based on accepted answer above by Kyle Kelley.

import urllib.request

word_url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib.request.urlopen(word_url)
long_txt = response.read().decode()
words = long_txt.splitlines()

Output:

>>> words
['a', 'AAA', 'AAAS', 'aardvark', 'Aarhus', 'Aaron', 'ABA', 'Ababa',
 'aback', 'abacus', 'abalone', 'abandon', 'abase', 'abash', 'abate',
 'abbas', 'abbe', 'abbey', 'abbot', 'Abbott', 'abbreviate', ... ]

And to generate (because it was my objective) a list of 1) upper case only words, 2) only "name like" words, and 3) a sort-of-realistic-but-fun sounding random name:

import random
upper_words = [word for word in words if word[0].isupper()]
name_words  = [word for word in upper_words if not word.isupper()]
rand_name   = ' '.join([name_words[random.randint(0, len(name_words))] for i in range(2)])

And some random names:

>>> for n in range(10):
        ' '.join([name_words[random.randint(0,len(name_words))] for i in range(2)])

    'Semiramis Sicilian'
    'Julius Genevieve'
    'Rwanda Cohn'
    'Quito Sutherland'
    'Eocene Wheller'
    'Olav Jove'
    'Weldon Pappas'
    'Vienna Leyden'
    'Io Dave'
    'Schwartz Stromberg'
🌐
Reddit
reddit.com › r/c_programming › generating a random word from an array
r/C_Programming on Reddit: Generating a random word from an array
February 6, 2022 -

As the title says it, I'm dropping here the code to get a random word from an array as it hasn't been mentioned on any forum

Here is the code:

#include<stdio.h>
#include<stdlib.h>
int main(){
int x=0;
int y;
char words[][10]={"cat","dog","giraffe","fly"};
for(int i=0;i<10;i++){
y=rand()%4+1;
}
printf("%s ",words[y]);

return 0;
}

This code gives also a random number, which is "y".

If you run this code you might get the same answers twice or maybe more but that is because the array is small but the more your array contains more words, the chance of getting the same word decreases.
Also in case you want to enlarge the array just change the number "4" to the number of elements in the array.

Have a nice day everyone.

🌐
DaniWeb
daniweb.com › programming › software-development › threads › 159921 › modifying-this-random-word-program
python - Modifying this random word program [SOLVED] | DaniWeb
import random # list of words words = ['python', 'jumble', 'easy', "difficult", "answer", "tracer", "muffin"] # Computer picks one word from the list word = random.choice(words) # create a variable to use later to see if the guess is correct correct = word print "Guess the word hint there are :", len(word) print "letters" guess = raw_input("\nYour guess:") guess = guess.lower() while (guess !=correct) and (guess !=""): if guess > word: print "Lower letter.." elif guess < word: print "Higher letter.." else: print "You guessed it correctly" guess = raw_input("\nYour guess:") guess = guess.lower() if guess == correct: print "That's it!
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 136320 › help-generate-random-word-function-from-fiveletter-txt-file
python - help! generate random word function from ... [SOLVED] | DaniWeb
If you want to pick more than one random word, than it would be more pythonic to read the file only once (a time consuming operation), and your code would look like this ... import random def getRandomFiveLetterWord(fileList): """ return a random word from the list strip off trailing whitespace """ randomWord = random.choice(fileList) return randomWord.rstrip() fh = open("fiveLetterWords.txt", "r") fileList = fh.readlines() fh.close() print "The Five-Letter Word Generator generates:", \ getRandomFiveLetterWord(fileList)
🌐
PyPI
pypi.org › project › random_word
random_word · PyPI
This is a simple python package to generate random English words.
      » pip install random_word
    
Published   Nov 21, 2024
Version   1.0.13
🌐
Reddit
reddit.com › r/learnpython › generate random word of specific length
r/learnpython on Reddit: Generate random word of specific length
November 15, 2022 -

I want to generate a random word of a specific length. I found a python module called random-word and this is my code.

from random_word import RandomWords
r = RandomWords()

# Return a single random word
r.get_random_word()

result = None
while result is None:
    try:
        word1 = r.get_random_word()
        print (word1)
        if len(word1) == 5:
            result = True
    except:
         print ('There was a problem')
# other code that uses result but is not involved in getting it

print (word1)
print (len(word1))

It works perfectly fine, but it's very slow. It takes about 10 to 15 seconds to run until it finds a word of that length. Does anybody have a better way of doing this? Another way I thought was to maybe have a dictionary file and iterate through that. The reason I don't like that approach is I don't really like the idea of having to have a file on the machine. Also if it iterates through the file it won't be random.

Any suggestions appreciated.

Thanks

🌐
PyPI
pypi.org › project › Random-Word
Random-Word
January 31, 2021 - JavaScript is disabled in your browser · Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
DEV Community
dev.to › lubiah › generating-random-words-in-python-2obi
Generating random words in python - DEV Community
September 10, 2021 - It contains a collection of string constants import random #Python's module for generating random objects lowercase_letters = string.ascii_lowercase #A constant containing lowercase letters def lowercase_word(): #The function responsible for generating the word lowercase word = '' #The variable which will hold the random word random_word_length = random.randint(1,10) #The random length of the word while len(word) != random_word_length: #While loop word += random.choice(lowercase_letters) #Selects a random character on each iteration return word #Returns the word random_word = lowercase_word()
🌐
Quora
thetechgurus.quora.com › How-to-create-a-random-list-of-words-in-Python
How to create a random list of words in Python - The Tech Guru ! - Quora
Answer: [code]import random random_words = ["word1", "word2", "word3", "word4", "word5", "word6", "word7", "word8", "word9"] random.shuffle(random_words) print(random_words) [/code]change the array of random words to your own words, you can ...
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › hardware and peripherals › raspberry pi pico › micropython
Print random word from a list (import random) - Raspberry Pi Forums
February 11, 2022 - (As an example a list of colors; Blue, Red, Green, Yellow) My ultimate goal is to print a word from a list to an LCD screen on a Pico at a button press but I'd be happy for anything to get me a few steps forward. Thank you, Bob ... import random letters = ['a', 'b', 'c', 'd', 'e', 'f'] print(random.choice(letters)) Replace the letters with your words.
🌐
Funprogramming
funprogramming.org › 54-Infinite-Forest-Combine-random-words-using-an-Array.html
Fun Programming - Infinite Forest? Combine random words using an Array
Arrays allow us to work with a collection of items of the same kind. For example, a list of numbers, or a list of words. In this episode we create two list of words and pick randomly one word from each list to create funny combinations. To declare an array we write square brackets behind the ...