[Tutor] A puzzle for you

Bob Gailer bgailer at alum.rpi.edu
Wed Oct 18 07:19:03 CEST 2006

John Fouhy wrote:
> >From the python_dev LiveJournal community ---
> Predict the outcome of the following code:
> ##
> from random import *
> seed()
> [choice(dict((x+1,0) for x in range(1000))) for x in range(693)][0]
> ##
Well the discussion did not go very far! You got my "prediction" and one 

It appears that (despite the docs) a dict is OK as an argument. choice 
uses len() to get the # of elements, picks a number between 0 and 
len()-1, and uses [] to access the chosen element. len() and [] both 
work with dicts.

So you have built a dict of 1000 items with keys between 1 and 1000, all 
values 0. Then you have give choice 693 tries to pick a key value other 
than 0. One 0 raises a key not found exception. No 0s raises no 
exception and the expression returns 0.

Bob Gailer

More information about the Tutor mailing list