List Length in {lang}
We can get the length of a list using the len() function like this:
ourList = [50, 40, 30]
# Printing the length:
print(len(ourList)) # Output: 3
# Changing the list:
ourList.pop()
# Printing the new length:
print(len(ourList)) # Output: 2
Using len()
We can use the len() function to access items from the end of a list.
Because lists are 0-indexed, the index of the last item is length - 1:
ourList = [50, 40, 30]
# Printing the last item:
print(ourList[len(ourList) - 1]) # Output: 30
# Printing the second to last item:
print(ourList[len(ourList) - 2]) # Output: 40
Assignment
Follow the Coding Tutorial and let's play with some arrays.
Hint
Look at the examples above if you get stuck.