How can random.shuffle cause a KeyError?

I just got the error:

Traceback (most recent call last):
  File "./download_documents.py", line 153, in <module>
    paragraphs, used_pages = find_pages(lang, to_extract)
  File "./download_documents.py", line 67, in find_pages
    random.shuffle(page_titles_queue)
  File "/usr/lib/python2.7/random.py", line 291, in shuffle
    x[i], x[j] = x[j], x[i]
KeyError: 1

Which confuses me a little.

  • random.shuffleseems to work with lists of null items and in single-item lists.
  • page_titles_queue - a list of tuples.
  • There are two lines after random.shuffle(page_titles_queue), page_titles_queue.pop()but this should not affect the shuffle. Correctly?

So what are the possible reasons for KeyError?

I use Python 2.7.12on Ubuntu 16.04.

+4
source share
1 answer

random.shuffle just exchanging elements, the line in which the exception occurred makes this very clear:

x[i], x[j] = x[j], x[i]

x - "", . i j range(0, len(x)), i j isn ' t, "", Exception. , , KeyError:

>>> import random
>>> d = {i: i for i in range(7, 10)}
>>> random.shuffle(d)
KeyError: 3

, , , range(0, len(x)):

>>> d = {i: i for i in range(10)}
>>> random.shuffle(d)
>>> d
{0: 7, 1: 9, 2: 3, 3: 4, 4: 0, 5: 2, 6: 1, 7: 6, 8: 8, 9: 5}

, , Exception. , :

d = {i: i for i in range(1, 10)}
random.shuffle(d)   # works sometimes, but sometimes it throws the KeyError
+2

Source: https://habr.com/ru/post/1684271/


All Articles