2.8 List operations
You can perform many of the same operations on lists as you can on strings, including slicing.
years = [2021, 1983, 1976, 1997, 1990]
years
[2021, 1983, 1976, 1997, 1990]
len(years)
5
years[0]
2021
years[-2]
1997
years[1:3]
[1983, 1976]
A major difference between strings and lists is that you can change the items in a
list
: lists are mutable.
years[0] = 2000
years
[2000, 1983, 1976, 1997, 1990]
With strings, you must construct a new and different string with any alterations. Strings are immutable, meaning that you cannot change their structure or contents. I can have a variable point to a new string, but I cannot change the string object itself.
letters = "abcd"
letters
'abcd'
letters[0] = "A"
TypeError: 'str' object does not support item assignment
...