Tutorial by Examples

Let's say you've got a list of restaurants -- maybe you read it from a file. You care about the unique restaurants in the list. The best way to get the unique elements from a list is to turn it into a set: restaurants = ["McDonald's", "Burger King", "McDonald's", &qu...
with other sets # Intersection {1, 2, 3, 4, 5}.intersection({3, 4, 5, 6}) # {3, 4, 5} {1, 2, 3, 4, 5} & {3, 4, 5, 6} # {3, 4, 5} # Union {1, 2, 3, 4, 5}.union({3, 4, 5, 6}) # {1, 2, 3, 4, 5, 6} {1, 2, 3, 4, 5} | {3, 4, 5, 6} # {1, 2, 3, 4, 5, 6} # Difference ...
Sets are unordered collections of distinct elements. But sometimes we want to work with unordered collections of elements that are not necessarily distinct and keep track of the elements' multiplicities. Consider this example: >>> setA = {'a','b','b','c'} >>> setA set(['a', 'c'...
We define two sets a and b >>> a = {1, 2, 2, 3, 4} >>> b = {3, 3, 4, 4, 5} NOTE: {1} creates a set of one element, but {} creates an empty dict. The correct way to create an empty set is set(). Intersection a.intersection(b) returns a new set with elements present in bot...
{{1,2}, {3,4}} leads to: TypeError: unhashable type: 'set' Instead, use frozenset: {frozenset({1, 2}), frozenset({3, 4})}

Page 1 of 1