The list
we saw is a container type: its purpose is to hold other objects.
We can ask python whether or not a container contains a particular item:
'Dog' in ['Cat', 'Dog', 'Horse']
True
'Bird' in ['Cat', 'Dog', 'Horse']
False
2 in range(5)
True
99 in range(5)
False
A list can be modified:
name = "John Philip Idris Doe".split(" ")
print(name)
[‘John’, ‘Philip’, ‘Idris’, ‘Doe’]
name[0] = "Dr"
name[1:3] = ["Griffiths-"]
name.append("PhD")
print(" ".join(name))
Dr Griffiths- Doe PhD
Note that ‘name[1:3]’ only replaces two elements of the list.
A tuple
is an immutable sequence which means that it cannot be modified:
my_tuple = ("Hello", "World")
my_tuple
(‘Hello’, ‘World’)
my_tuple[0]="Goodbye"
—————————————————————————
TypeError Traceback (most recent call last)
<ipython-input-9-98e64e9effd8> in <module>()
—-> 1 my_tuple[0]=”Goodbye”
TypeError: ‘tuple’ object does not support item assignment
str
is immutable too:
fish = "Hake"
fish[0] = 'R'
—————————————————————————
TypeError Traceback (most recent call last)
<ipython-input-10-fe8069275347> in <module>()
1 fish = “Hake”
—-> 2 fish[0] = ‘R’
TypeError: ‘str’ object does not support item assignment
This means that we cannot change individual elements of a tuple or string.
But note that container reassignment is moving a label, not changing an element:
fish = "Rake" ## OK!