Tuples and Sets
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] b='asdfasdf' c=(4,9,a,b,'zxcv') print(c) print(type(c))
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[1]=99
will 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.
a={3,4,5,6,7,9} print(a) print(type(a)) b={3,3,3,4,4,4,5,5,6,7,8} print(b) print(type(b))
You should observe that both b
and c
contain the same set of objects. The next set of commands should demonstrate Python's ability to perform set operations.
a={3,4,5} b={4,5,6,7,8,9} c=a.intersection(b) print(c) d=a.union(b) print(d) e=8 print(e in b) print(e in a) f=b.difference(a) print(f)
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.
Source: Gerry Jenkins, https://www.youtube.com/watch?v=aw4Hn1s3wcM
This work is licensed under a Creative Commons Attribution 3.0 License.