Sets in Python

Ran into a problem that needed set as a tool to solve it.

What is a set?

A set is a collection of unordered unique objects.

What are the common operations

Intersection, union subset and so on.

Operation     Result
len(s)      number of elements in set s (cardinality)
x in s      test x for membership in s
x not in s      test x for non-membership in s
s.issubset(t)     test whether every element in s is in t
s.issuperset(t)  test whether every element in t is in s
s.union(t)     new set with elements from both s and t
s.intersection(t)      new set with elements common to s and t
s.difference(t)    new set with elements in s but not in t
s.symmetric_difference(t)     new set with elements in either s or t but not both
s.copy()        new set with a shallow copy of s

What it can’t do

Slicing, indexing and other things that associated with orders.

Hashing?

Can we hash sets?

No we can not hash sets since set is mutable.So set doesn’t have the hash function in its class.

What if we want to have a set of set?

We will talk about immutable Set soon. It is a set that’s immutable therefore we can subsequently use it as a object to hash

Set classes implementation

It is implemented using a dictionary so it requires objects in the set to have hash() and eq()

Immutable set

As the name indicate, it is a set that doesn’t change and subsequently has a hash() function.

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax