简体   繁体   中英

Index error when drawing elements by index from list using random.randint()'s

import random
fruits = ['Apple','Mango','Banana','Grapes','Guava']
random.seed(500)
low =0
high = len(fruits)
random_fruits = [fruits[random.randint(low,high)] for i in range(1000)]

This is my code and following is the error what I am getting?

IndexError: list index out of range

Function random.randint generates a random number inside the range defined by low and high values, both included: low <= x <= high . Since you set high to len(fruits) , and the last list index is actually len(fruits) - 1 , you can get a list index out of range error in case random.randint produces the high value.

Instead, modify the code by changing the definition of high .

import random
fruits = ['Apple','Mango','Banana','Grapes','Guava']
random.seed(500)
low = 0
high = len(fruits) - 1
random_fruits = [fruits[random.randint(low,high)] for i in range(1000)]

You are calling one function 1000 times to get 1000 values. For you can simplify your code by using random.choices(iterable, k=nubmer of elements) .

One call will give you a list of 1000 random items from your source-iterable:

import random

fruits = ['Apple','Mango','Banana','Grapes','Guava']
random.seed(500)
# reduced 1000 to 10 for output-brievity
random_fruits = random.choices(fruits,k=10) # no need to get 1000 times one element, get
                                            # 1000 back in one call is more efficient.

print(random_fruits)

Which gives an output of:

['Grapes', 'Guava', 'Banana', 'Mango', 'Grapes', 'Mango', 'Guava', 'Mango', 'Banana', 'Grapes']

You feed it an iterable and a count and get the radomn drawn results (with duplicates) back as list .


Timings:

import timeit

s = """import random
random.seed(500)
fruits=['Apple','Mango','Banana','Grapes','Guava']"""

timeit.timeit("k = [fruits[random.randint(0,4)] for _ in range(1000)]", 
              setup = s , number=100) 

0.11539360368355066

vs.

timeit.timeit("k = random.choices(fruits, k=1000)", 
              setup = s, number=100)

0.02338418321748037

which makes using random.choices(...) about 5 times faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM