Check your understanding of the previous reading: indexing, comparing, testing membership, and adding to a list.

Question 1

What is the value stored in my_var after the following strange code is executed?

my_var = [1, 2, 3][1]

Select one answer, then check.

  • Not quite. The trailing [1] indexes into the list literal; the result is a single element, not the whole list.
  • Not quite. Indexing with a single number, not a slice, returns the element itself, not a one-element list.
  • Not quite. Indexing with a single number returns the element itself, not a one-element list.
  • Not quite. Index 0 would be 1, but this code indexes at 1.
  • Correct. [1, 2, 3] creates the list, and [1] right after it indexes at position 1, the second element: 2.
  • Not quite. Creating a list and immediately indexing it is valid Python, as shown in the reading's print([2][0]) example.

Question 2

What is the value stored in my_var after the following code is executed?

my_var = [1, 2, 3] < 5

Select one answer, then check.

  • Not quite. Python has no rule for comparing a list to a number with <, so this line never produces a boolean.
  • Not quite. Python has no rule for comparing a list to a number with <, so this line never produces a boolean.
  • Correct. Comparing a list to an integer with < raises a TypeError; Python cannot decide which is "less" between a list and a number.

Question 3

What is the value stored in my_var after the following code is executed?

my_var = 5 in [1, 3, 5]

Select one answer, then check.

  • Correct. 5 is an exact element of [1, 3, 5], so the membership test succeeds.
  • Not quite. 5 is in the list [1, 3, 5], so in returns True.
  • Not quite. Testing membership of a number in a list of numbers is perfectly valid Python.

Question 4

What is the value stored in my_var after the following code is executed?

my_var = [1, 2, 3] + 4

Select one answer, then check.

  • Not quite. The reading is explicit that you cannot add elements to a list with + - you need the append method for that.
  • Not quite. The + 4 is not silently ignored; it causes an error instead.
  • Not quite. Python does not sum a list's elements when you add a number to it.
  • Correct. You cannot add elements to a list using + with a plain number; + on a list expects another list, so this raises a TypeError.

Question 5

Which of the following demonstrates how to add something to the following list variable?

temperatures = [44, 36, 72]

Select one answer, then check.

  • Not quite. append is a method on the list itself, not a standalone function you call with the list as an argument.
  • Not quite. This is not valid Python syntax at all.
  • Correct. append is called as a method on the list, adding 42 to the end of temperatures in place.
  • Not quite. The reading shows this exact mistake causing an error - + does not work between a list and a number.
  • Not quite. This replaces the whole list with the number 42; nothing is added to it.