K
K
kommov2018-02-02 11:44:12
Python
kommov, 2018-02-02 11:44:12

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

1 answer(s)
B
bbkmzzzz, 2018-02-12
@bbkmzzzz

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]

Here is the index call, and to generate a random number, it takes the length of the sequence. See Why the list is empty or inaccessible if it is a shared resource.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question