M&C9: A list can contain a list?

Yes, a list can contain a list. In some applications, this ability is needed and can be very useful. The example below illustrates the use of accessing list elements in a list containing an element that is a list.

Example

L = [[1, 2, 3], [4, 5, 6], [“fox”, “hen”], 66]

  • L is a list of length 4
  • L[0] = [1, 2, 3]
  • L[0][2] returns 3, the 3rd element of list L[0]
  • L[2][1] returns ‘hen’, the 2nd element of list L[2]

mc9