0

I'm looking for a better way to randomly select an item from a list in Python. I've done some research. My goal is to select a random element from the randomName() function.

import random

def randomName():
    names = ["Morpheus","Neo","_from_redpills","Agent Smith","Trinity"]
    num = random.randint(0, len(names)-1)
    return names[num]`

for z in range(5):
    print randomName()
Makoto
  • 104,088
  • 27
  • 192
  • 230
  • Your title was a bit lacking (it doesn't include the word "random"), but a Google search for "I'm looking for a better way to randomly select an item from a list in Python" produces lots of useful results. – TigerhawkT3 Dec 25 '15 at 01:47

1 Answers1

1

Good question. Python has a good way to do this with another part of the random module. You can use random.choice(NameOfList). This will pick a random element from the list.

def randomName(): names = ["Morpheus","Neo","_from_redpills","Agent Smith","Trinity"] return random.choice(names)

ION28
  • 64
  • 4