Set

Mutable, unordered, unique objects. Elements must be hashable.

Advantages: Searching is O(1). Lots of useful methods.

Disadvantages: Not ordered. Elements must be hashable.

Creating

# create a empty set
s = set()

# create a set with elements
s = {1,2,3}        # Python 2.7, 3.x

Creating from another type

s = set([1,2,3])      # From list
s = set((1,2,3))      # From tuple
s = set('abc')        # From string

Adding a value

s = {1,2,3}
s.add(4)
s             # {1,2,3,4}
s.add(4)
s             # {1,2,3,4} — duplicates are ignored

Adding multiple values

s = {1,2,3}
s.update([3,4,5])     # Any iterable will do
s                     # {1,2,3,4,5} — duplicates ignored

Removing an element

s = {1,2,3}
s.remove(1)
s            # {2,3}

Last updated