""" Ex. 2.15 from "A primer on...", Index a nested list and check the result. This exercise was not done in the lecture but is useful to do on your own as a quick check that you understand nested lists """ q = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']] #a) print(q[0][0]) #the letter a, first element in first list print(q[1]) #the list ['d', 'e', 'f'], the second element of the outer list print(q[-1][-1]) #the last element h, the last element of the last list print(q[1][0]) #the 'd' element, q[1] gives the second list, q[1][0] gives its first element print(q[-1][-2]) #q[-1] gives the last list, q[-1][-2] gives the second-to-last element of this list, i.e., 'g' #b) A nested for loop traverses all elements: for i in q: for j in range(len(i)): print(i[j]) """ Here, the objects are of type list, since they are the elements of the outer list q. The inner loop is constructed differently, using range(...) and indexing, so the j objects are integers. The printed values i[j] have type str. """ """ Terminal> python index_nested_list.py a ['d', 'e', 'f'] h d g a b c d e f g h """