Lucas
Lucas

Reputation: 126

Python - empty range for randrange() (0,0, 0) and ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))

When I run this program: (python 3.3.1)

import random
import time
from random import randrange
print(' ')
print('I am thinking of a person...')
time.sleep(1)
print('He or she belongs to this group of people:')
people = 'Alice Elise Jack Jill Ricardo David Jane Sacha Thomas'.split()
loop = 0
while loop != 6:
    group = []
    person = randrange(0, len(people))
    personName = people[person]
    int(person)
    group.append(personName)
    del people[person]
    loop = loop + 1

I sometimes get this error message:

Traceback (most recent call last):
  File "C:\Users\user\Python\wsda.py", line 132, in <module>
    person = randrange(0, len(people))
  File "C:\Python33\lib\random.py", line 192, in randrange
    raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop,     width))
ValueError: empty range for randrange() (0,0, 0)

Basically i want it to get 6 random names from the variable 'people' and add it to the variable 'group'...

Also this is part of a larger program based on the guess who game... Could someone please tell me how to fix this? Thx

Upvotes: 3

Views: 28961

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121614

The error occurs when the people list is empty (length 0). You may want to test for that:

>>> import random
>>> random.randrange(0, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mj/Development/Libraries/buildout.python/parts/opt/lib/python2.7/random.py", line 217, in randrange
    raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
ValueError: empty range for randrange() (0,0, 0)

If you need to add 6 random choices from the people list it is better to shuffle the people list and then add the first 6 of that list to group:

import random

people = 'Alice Elise Jack Jill Ricardo David Jane Sacha Thomas'.split()
random.shuffle(people)
group.extend(people[:6])
people = people[6:]  # remainder, so the 6 picks have been removed

but chances are of course you end up with an empty list again at some point.

Another approach is to just use random.sample():

people = 'Alice Elise Jack Jill Ricardo David Jane Sacha Thomas'.split()
group.extend(random.sample(people, 6))

This just picks 6 random names from the list, but leaves people unaffected and a future pick of 6 names could repeat names.

Upvotes: 5

Related Questions