10.6. Nested ListsΒΆ

A nested list is a list that appears as an element in another list. For example:

The list nested is a lists of lists. Each inner list can be a different length, but they all must be lists of ints. If we print nested[3], we get [10, 20]. To extract an element from the nested list, we can proceed in two steps. First, extract the inner list, then extract the item of interest. It is also possible to combine those steps using bracket operators that evaluate from left to right.

Check your understanding

    list-23-1: What is printed by the following statements?

    a_list: [[int]]
    a_list = [[4, 6, 8], [777, 888, 999]]
    if a_list[0][1] < 100:
       print(a_list[1][0])
    else:
       print(a_list[1][1])
    
  • 6
  • 6 is in the wrong list. alist[1] refers to the second item in a_list, namely [777, 888, 999].
  • 8
  • 8 is in the wrong list. alist[1] refers to the second item in alist, namely [777, 888, 999].
  • 777
  • Yes, a_list[0][1] is 6 which is less than 100 and a_list[1] is the second list, the first item is 777.
  • 888
  • alist[0][1] is 6 which is less than 100. Take another look at the if statement.
You have attempted of activities on this page
10.5. Concatenation"> 10.7. Nested Iteration">Next Section - 10.7. Nested Iteration