Python Basics : Part 7 – Sets

A Set in python is a collection of unique elements. Curly brackets are used to define a set. If you have a bunch of integers and you need to pick only the unique numbers among them, you can make use of python sets. We can use a set function to pass a list of values and the output set will contain the unique elements.

In [1]: {1,2,3,4,3,4,5}
Out[2]: {1,2,3,4,5}

In [3]: set([1,1,1,2,2,3,3,4,5])
Out[4]: {1,2,3,4,5}

We can even add items to the sets by using the add method as shown below :

In [5]: set={1,2,3}
In [6]: set.add(4)
In [7]: set
Out[8]: {1,2,3,4}

Note that the element is added to the end of the set. Try to add 4 again to the set and let me know what happens in the comments section below.