Python Sets

Creating and Accessing:

mySet = {"myVal1", "myVal2", "myVal3"} # Create a set with 3 values print( "myVal1" in mySet ) # Display True if Set contains a specifed value

- A set is like a list of distinct items, it can only store one of each item, it will ignore addition of an item that it contains

- Sets are useful for defining groups and comparing their relationships

- A set can be of different types, including multiple types in the same set

- You can also create a set from a list with set(myList)

Add Items:

mySet.add("myAddedVal") # Add one mySet.update(["val5", "val6"]) # Add multiple

Remove Items:

mySet.remove("myVal1") # Remove one (error if not there) mySet.discard("myVal2") # Remove one (no error if not there) mySet.clear() # Remove all values

Operations:

mySet1 & mySet2 # Intersection (values in common) mySet1.intersection(mySet2) # Alternative way to get intersection mySet1.union(mySet2) # All values among both mySet1.issubset(mySet2) # True if set2 contains all values of set1 mySet1.issuperset(mySet2) # True if all values of set2 are contained in set1 mySet1.difference(mySet2) # Returns set with items unique to set1 (in set1 but not set2) mySet1.symmetric_difference(mySet2) # True if in one set or other but not at intersection

- These are ways that relationships between groups are explored

Challenge

Create a set that contains teh numbers from 10 to 20, and another set with the prime numbers from 2 to 19. Display the numbers that are in common between the two sets, and then display the numbers that are unique to the second set.

Completed