Answer the question
In order to leave comments, you need to log in
Why does Python throw an IndexError: list index out of range error with correct code?
There is an elementary part of the code that throws a random element from the list into the variable. Something like this:
...
text_list = ['text1', 'text2', 'text3', 'text4']
get_text = random.choice(text_list)
...
And then we work with this variable. The list text_list - does not change anywhere. There are no hits on indexes. And it was on the line get_text = .. that the IndexError: list index out of range error often began to fly out. I don't get it, how is this possible? Most of the time the code works flawlessly, but sometimes it seems like the python starts to go crazy - on all random.choice the error index starts to fly out (the lists are all immutable and local!). The only point is that the code works in a multithread, there are more than 1k threads. But the variable is local to each object. Can anyone suggest what is causing this and how to avoid it? Not to wrap in try except such a primitive that should not lag? Maybe the problem is just that the error crashes when many threads simultaneously try to access an element of a common list?
Answer the question
In order to leave comments, you need to log in
random.choice throws an exception if the sequence is empty.
random.choice source
def choice(self, seq):
"""Choose a random element from a non-empty sequence."""
try:
i = self._randbelow(len(seq))
except ValueError:
raise IndexError('Cannot choose from an empty sequence') from None
return seq[i]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question