We have introduced the concepts of mutable and immutable objects in Python. Recall that lists are mutable while strings are immutable. This section introduces two more immutable data types useful for holding collections of objects: tuples and sets.
In short, tuples are immutable lists. Similar to strings, they cannot be changed once they have been assigned. Everything that you have learned so far about indexing and slicing also applies to tuples. The syntax for forming a tuple uses parentheses (instead of square brackets for forming a list):
a=[23.7, 45, 78]
Notice that we can put any object we please into the tuple defined as the variable
c. The output after running this code looks almost exactly like a list. However, because of the immutability of
c, attempting to modify an element with an instruction such as
c=99will result in an error. One obvious use for tuples for holding data that must be write-protected. We will see other uses when we encounter dictionaries.
Sets are another immutable data type that holds a unique collection of objects. Sets can be used to perform typical set operations such as union, intersection, set differences, and so on. Duplicates values are not possible within a set. Left and right squirrely brackets are used to assign sets.
You should observe that both
c contain the same set of objects. The next set of commands should demonstrate Python's ability to perform set operations.
print(e in b)
print(e in a)
This code introduces fundamental operations such as set membership (using the
in keyword) and a suite of set method calls for computing the union, intersection, and so on.