Unlike other languages, Python does not throw an error when we try to access list elements with negative indexes.
For example, we can use the index -1 to select the last element of a list, even when we don’t know how many elements are in a list:
words = ["car", "egg", "plant", "flag"]
print(words[-1]) # Output: "flag"
In general, writing nums[-x] is equalivalent to writing nums[len(nums) - x]. We can access every element of a list using negative indexes:
words = ["car", "egg", "plant", "flag"]
print(myList[-1]) # Output: "flag"
print(myList[-2]) # Output: "plant"
print(myList[-3]) # Output: "egg"
print(myList[-4]) # Output: "car"
Assignment
Follow the Coding Tutorial and let's play with some arrays.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
