Set and Boolean

Sets and Booleans are the two simple object types in python.

Set

A set is an unorderedd collection of unique elements.

We can create a set using set() function.


In [1]:
a = set()

In [2]:
a


Out[2]:
set()

Now a is a set. To insert values into a set we use add().


In [3]:
a.add(1)

In [4]:
a


Out[4]:
{1}

In [5]:
a.add('string')

In [6]:
a


Out[6]:
{1, 'string'}

In [7]:
a.add(3.1415)

In [8]:
a


Out[8]:
{1, 3.1415, 'string'}

The values in a set can be of any type. But they should be unique accross the set.


In [9]:
a.add(1)

In [10]:
a


Out[10]:
{1, 3.1415, 'string'}

Notice that when we try to add a duplicate value it is not inserted.


In [11]:
a.add('string')

In [12]:
a


Out[12]:
{1, 3.1415, 'string'}

Removing an element from a set


In [13]:
a.discard(1)

In [14]:
a


Out[14]:
{3.1415, 'string'}

We can use discard() to remove an element from a set permanently. We can also use remove(), but if the value passed is not an element of the set remove returns an error and discard does nothing.


In [15]:
a.discard(4)

In [16]:
a


Out[16]:
{3.1415, 'string'}

In [17]:
a.remove(4)


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-17-1ace18a8c563> in <module>()
----> 1 a.remove(4)

KeyError: 4

Booleans

Python comes with Booleans (with predefined True and False displays that are basically just the integers 1 and 0). It also has a placeholder object called None.


In [18]:
b = True

In [19]:
b


Out[19]:
True

All the comparision operations return boolean.


In [20]:
22 > 3


Out[20]:
True

In [21]:
n = 10
n < 100


Out[21]:
True

In [22]:
n > 98


Out[22]:
False

We can also use None place holder for any object type in python to simply initialize the object with nothing. You can think of it as NULL.


In [23]:
b = None

In [24]:
b

See there is nothing in b. We can assign any type of value to b.


In [25]:
b = 'Sample string'

In [26]:
b


Out[26]:
'Sample string'