Can you remove things from lists? / removing things from lists
One way to remove things from lists is with the del
function.
>>> school = list("Swarthmore")
>>> school
['S', 'w', 'a', 'r', 't', 'h', 'm', 'o', 'r', 'e']
>>> del school[0]
>>> school
['w', 'a', 'r', 't', 'h', 'm', 'o', 'r', 'e']
I''m still not sure what immutable vs mutable means?
The short version is: Mutable things can be changed, and immutable things can't be changed. So for example we can change the first item in a list, but we can't change the first character in a string:
>>> school = "Swarthmore"
>>> school[0] = "G"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> schoolList = list("Swarthmore")
>>> schoolList
['S', 'w', 'a', 'r', 't', 'h', 'm', 'o', 'r', 'e']
>>> schoolList[0] = "G"
>>> schoolList
['G', 'w', 'a', 'r', 't', 'h', 'm', 'o', 'r', 'e']
If you use a negative number, can you index backwards? Like lst[-1] goes backwards 1.
Yes, you can do this. So to get the last item in a list, you can do lst[ (len(lst)-1) ]
or lst[-1]
.
How do lists handle multiple variable types? / can multiple different types exist in one list?
In Python, yes: you can have a list like [2, "cat", 5.8]
. But in other programming languages, this will cause an error. This will also probably cause your professor to frown and, deep down inside, be saddened. So please don't do this.
When are lists most useful?
ALL THE TIME.