-1

Possible Duplicate:
How do I randomly select an item from a list using Python?

I am trying to create a string that uses 3 different lists for 3 different words:

print (word1[random.randint(0, X )],
       "the",
       word2[random.randint(0, X)],
       word3[random.randint(0, X)])

word1,word2 and word3 are different lists.

The X in randint is the amount of strings in the respective lists.

So, could anybody help me out and tell me how i write this code correctly?

word1[random.randint(0, [amount of strings in list "word1"])]
Community
  • 1
  • 1
user1275670
  • 1,215
  • 2
  • 8
  • 9

4 Answers4

3

You're making an unwarranted assumption that you need to pick such a random number. The random number is not the thing that you want; you want a random element of the string.

To make a random choice from a sequence, use random.choice.

print(random.choice(word1), "the", random.choice(word2), random.choice(word3))
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • Woowh. Thanks mate... ive been wanting to do this for several weeks now, but i guess my teacher is a dumbass XD forcing us to learn stuff that has too much math (vectors n stuff) and not even explaining anything that has to do with programming. – user1275670 Mar 15 '12 at 20:32
  • Your teacher probably honestly believes that getting you to think in these "mathematical" terms will actually improve your programming instincts and ability to break down a programming problem logically. This misconception is frighteningly common. – Karl Knechtel Mar 15 '12 at 21:01
  • @ChaosPointDK - you can learn the library by reading the tutorials at python.org. – D.Shawley Mar 16 '12 at 16:56
0

randrange: http://docs.python.org/library/random.html#random.randrange

Marcin
  • 48,559
  • 18
  • 128
  • 201
0

len() gets the length of something. Using len(word1) would get the number of items in the list. What I assume you want to do is pick a random word from the list. random actually has its own module to do that. You would use random.choice(word1) to get a random item from word1.

CoffeeRain
  • 4,460
  • 4
  • 31
  • 50
0

Simple : word1[randomint(0, len(word1)-1)]

simlmx
  • 999
  • 12
  • 17