Hwoa Rang
Hwoa Rang

Reputation: 33

Select a random element from an array

I am trying to select a random element from my array.

However, sometimes I am getting an index out of bounds error, even though I accounted for the array starting at 0 by adding 1 to the maximum value of the index.

from random import randint

names = ['Sam', 'Paul', 'Mark', 'Simon', 'Sean', 'Samantha', 'Ellen']
random_name = names[randint(0, len(array)+1)]

print(random_name)

I only get an index out of bounds error sometimes?

Upvotes: 3

Views: 3086

Answers (2)

Sash Sinha
Sash Sinha

Reputation: 22350

Instead of adding 1 you need to subtract 1 from the length of the names, since in python the initial element of a list is assigned the index 0:

random_name = names[randint(0, len(names)-1)]


Alternative solution

However, for this particular case, I think using random.choice would be more appropriate, especially since you don't have to worry about list indexes at all when you use it:

>>> import random
>>> names = ['Sam', 'Paul', 'Mark', 'Simon', 'Sean', 'Samantha', 'Ellen']
>>> random.choice(names)
'Mark'

Upvotes: 2

Mike Tung
Mike Tung

Reputation: 4821

why not just use choice?

import random

names = ['Sam', 'Paul', 'Mark', 'Simon', 'Sean', 'Samantha', 'Ellen']
random_name = random.choice(names)

print(random_name)

Upvotes: 3

Related Questions