vikash.patel97
vikash.patel97

Reputation: 33

empty range for randrange() (1,1,0)

I am trying to split a list into training data and test data using a while loop but immediately after running for an iteration or two, randrange() error pops up. Can't understand what has gone wrong. The csv file ingested has 767 rows of data. Below is the code:

dataset = list(csv.reader(open("Data\diabetes.csv", 'r'), delimiter = ","))

trainSet = []
trainSize = int(0.67* len(dataset))
while len(trainSet) < trainSize:
      x = len(dataset)
      index = random.randint(1, x-1)
      trainSet.append(dataset[index])
      dataset = dataset.pop(index)

Following is the error:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
  File "C:\Users\Vikash Patel\AppData\Local\Programs\Python\Python38\lib\random.py", line 248, in randint
   return self.randrange(a, b+1)
  File "C:\Users\Vikash Patel\AppData\Local\Programs\Python\Python38\lib\random.py", line 226, in randrange
   raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))

ValueError: empty range for randrange() (1, 1, 0)

Upvotes: 3

Views: 1321

Answers (1)

Derek O
Derek O

Reputation: 19565

ValueError: empty range for randrange() (1, 1, 0) occurs when you try to call random.randint(1, 0)

This is happening because the line dataset = dataset.pop(index) is setting your dataset equal to the item that was popped off (which has length 1), when you want the dataset with the item popped off. Then when your loop iterates the next time around, x = len(dataset) sets x = 1, and the line index = random.randint(1, x-1) calls random.randint(1, 0).

Try this instead:

import random

dataset = [10,11,12,13,14,15]

trainSet = []
trainSize = int(0.67* len(dataset))
while len(trainSet) < trainSize:
    x = len(dataset)
    index = random.randint(1, x-1)
    trainSet.append(dataset[index])

    # this changes the size of the dataset
    dataset.pop(index)

Output:

> trainSet
[13, 12, 15, 14]

Upvotes: 1

Related Questions