6.8) Nested Lists: Accessing Non-Existing Elements
If you try and refer to an element that doesn’t exist, you will get an IndexError or TypeError:
>>> L1 = [ 1, [45,57,23,32], 'twenty one', [24,52], 99 ] >>> L1[1][3] 32 >>> L1[2][4] # remember, strings are indexed like lists ‘t’ >>> L1[0][1] # this element doesn’t exist Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> L1[0][1] TypeError: 'int' object has no attribute '__getitem__' >>> L1[3][2] # this element doesn’t exist neither Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> L1[3][2] IndexError: list index out of range
In the first case, L1[0] is an integer and trying to get an element of an integer (in this example, with the index [1]) doesn’t make sense. In the second case, you’re trying to get the third element in a list of length 2; the list is too short!