Multiple choice assessment: List comprehension

Jun 12, 2013 • Karmel Allison
  1. Which of the following will raise an exception?

a. my_list = [x2 for x in (1,2,3,4)]
b. my_list = [x
2 for x in (‘a’,’b’,’c’,’d’)]
c. my_list = [x2 for x in 1234]
d. my_list = [x
2 for x in ‘abcd’]

  1. What is the difference between list comprehension and a generator?

a. A generator does not guarantee the ordering of items.
b. List comprehension is faster when using built-in functions.
c. List comprehension does not require holding iterated objects in memory.
d. A generator does not allow list methods like slicing.

(Notably, #2 is not strictly a “why” question, but I think it still gets at teasing out usage reasoning rather than straightforward usage facts…)