Reid's Python Quiz

Python 2.5 is relatively recent and not supported everywhere yet, so it's important to understand the behavior of both Python 2.5 and earlier versions.

  1. (a) What number does the following code print?
    adders = []
    for i in range(0, 100):
        adders.append(lambda x: x+i)
    
    print adders[17](42)
    
    (b) What about the following similar-looking code?
    adders = [lambda x: x+i for i in range(0, 100)]
    print adders[17](42)
    
  2. (pre-Python 2.5 only) What does the following code print? Partial credit for approximately correct answers. (Hint: the function that exits a program is called sys.exit.)
    try:
        exit(0)
    except Exception, e:
        print e
    
  3. What number does the following code print?
    units = [1, 2]
    tens = [10, 20]
    nums = (a + b for a in units for b in tens)
    units = [3, 4]
    tens = [30, 40]
    print nums.next()
    
  4. Which of these lines produce the same output?
    print "word" in [] == False
    print ("word" in []) == False
    print "word" in ([] == False)
    

Answers