CMPE 150

Introduction to Computing

Fall 2021

Created by Gökçe Uludoğan

### Sets * An unordered collection of items. * Mutable (i.e. the items can be added or removed.) * Used to perform set operations like union, intersection, etc. * Created by using either curly braces {} or the built-in set() function. ```python my_set = {1, 2, 3} my_set = set([1.0, "Hello", (1, 2, 3)]) ```
### Properties * Each item is unique (no duplicates). * Each item must be immutable (cannot be changed). ```python my_set = {1, 2, 3, 4, 3, 2} print(my_set) my_set = set([1, 2, 3, 2]) print(my_set) my_set = {1, 2, [3, 4]} ``` Output ```python {1, 2, 3, 4} {1, 2, 3} Traceback (most recent call last): File "", line 15, in my_set = {1, 2, [3, 4]} TypeError: unhashable type: 'list' ```
### Modifying a set * add(): adds a single item * update(): adds multiple items ```python y_set = {1, 3} print(my_set) my_set.add(2) print(my_set) my_set.update([2, 3, 4]) print(my_set) ``` Output ``` {1, 3} {1, 2, 3} {1, 2, 3, 4} ```
### Removing elements from a set * discard(): removes an item. * remove(): removes an item. Raises an error if the item is not present. ```python my_set = {1, 3, 4, 5, 6} my_set.discard(4) print(my_set) my_set.remove(6) print(my_set) my_set.remove(2) ``` Output ``` {1, 3, 5, 6} {1, 3, 5} Traceback (most recent call last): File "", line 28, in KeyError: 2 ```
### Removing elements from a set * pop(): removes and returns an arbitrary item. ```python my_set = {1, 3, 4, 5, 6} print(my_set.pop()) ```
### Set operations **Union** ```python A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A | B) # or print(A.union(B)) ``` Output ``` {1, 2, 3, 4, 5, 6, 7, 8} ```
### Set operations **Intersection** ```python A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A & B) # or print(A.intersection(B)) ``` Output ``` {4, 5} ```
### Set operations **Set Difference** ```python A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A - B) # or print(A.difference(B)) print(B - A) # or print(B.difference(A)) ``` Output ``` {1, 2, 3} {6, 7, 8} ```
### Set operations **Symmetric Difference** ```python A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A ^B) # or print(A.symmetric_difference(B)) ``` Output ``` {1, 2, 3, 6, 7, 8} ```

References

  1. https://www.programiz.com/python-programming/set