This is the list I typed in:
numbers = [[1,'one'],[2,'two'],[3,'three'],[4,'four'],[6,'six']]
I’m lost on why numbers[-1][-1][-1] would return 'x'.
This is the list I typed in:
numbers = [[1,'one'],[2,'two'],[3,'three'],[4,'four'],[6,'six']]
I’m lost on why numbers[-1][-1][-1] would return 'x'.
This is because the first [-1] gets the last element in the list [[1,'one'],[2,'two],[3,'three'],[4,'four'],[6,'six']], which is [6, 'six'].
Then, the second [-1] gets the last element in that list, which is six.
Finally, the third [-1] returns the last character in the string six, which is x.
The square brackets ([]) tell python to get something at an index, and -1 is the last one. Strings can be thought of as lists of characters, which is why the x is return from that string.
-1 index, means the last element of a list. that you can see
e0 = in_nums[-1] # [6, 'six']
e1 = e0[-1] # 'six'
e2 = e1[-1] # 'x'
This happens because when you acess the -1 element on a list or a string, you are actually acessing the item on the last index of that list (or str). That said, we have:
numbers[-1] -> [6, 'six'] # returns the last element (a list)
numbers[-1][-1] -> 'six' # returns the last element of the above list
numbers[-1][-1][-1] -> 'x' # returns the last element of the above str