1. Home
2. Docs
3. Python 101 – Python Programming for Beginners
4. Set and Frozenset

# SET and FROZENSET

## What is a set ?

A set is a finite collection of unique elements.

Set is also a sequence, and it is iterable.

Unlike list or tuple, set can not have duplicate values.

set is an un-ordered collection of object.

A set is mutable; we can add, modify and delete elements from a set.

## How to create a set ?

Method 1:

A set is created by using set(iterable) constructor function.

set() creates an empty set

empty_set = set()

set can also be created by iterable object.

Example :

creating a set from iterable, list or tuple

list_numbers = [1,2,3,4,5,2,3,4]

tuple_numbers = 10,20,30,40,50,10,30,50

```#creating a set with list

set_num_1 = set(list_numbers)```

output:

```#note duplicates are removed

>>> set_num_1
{1, 2, 3, 4, 5}```

```#creating a set with tuple
set_num_2 = set(tuple_numbers)```

output:

```#note duplicates are removed
>>> set_num_2
{40, 10, 50, 20, 30}```

Method 2:

We can also Create a set with ‘{}’ curly brackets.

`>> a = {1,2,3,4,5,12,3,4}      #contains duplicate while defining`

```#check the contents of the set,

>>> a
{1, 2, 3, 4, 5, 12}    # actual set doesn't contain duplicates```

### set() is an un-ordered collection.

Python internally optimizes the order of the elements.

#Notice the order while defining and accessing.

Ex 1.

```>>> a = {4,5,6,1,2,4,5,56,23,6,11}
>>> a
{1, 2, 4, 5, 6, 11, 23, 56}```

Ex 2.

```>>> b = {33,4,2,55,6,1,2,22,18,900}
>>> b
{33, 2, 1, 4, 900, 6, 18, 22, 55}

```

### set can contain different types of immutable objects.

In this example mixed_set contain, integer, float, string, tuple

Example:

`>>> mixed_set = {1,1.0, "string",(110,20,30)}`

```#check the contents of the set
>>> mixed_set
{1, (110, 20, 30), 'string'}

```

## Built-in functions on sets

Lets look at how to use some built-in functions on Python.

Here the few built-in functions we are going to apply on sets.

help(),dir(), len(), min(), max(), sum(), sorted().

### dir(set)

Lists the names in current scope comprising attributes of set.

### len(set)

Returns number of items in set.

Example :

`a = {1, 2, 3, 4, 5}`
`>>> len(a)`

output:

`5`

### min(set)

Returns minimum value of the set.

```>>> min(a)
1```

### max(set)

Returns maximum value of the set.

```>>> max(a)
5```

### sum()

Returns sum of all the elements if items are numbers.

Ex 1:

```>>> sum(a)
15```

Ex 2:

For set with strings sum() throws TypeError, as doesn’t make sense to get a sum of strings.

Lets check that.

We have str_set with element type as strings.

`>>> str_set = {'one', 'two','three','four'}`
```>>> str_set
{'two', 'one', 'four', 'three'}

```

#check sum function on set.

`>> sum(str_set)`

ouput:

```Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>```

### sorted(set)

Returns a copy of sorted set, if set is not empty.
Otherwise returns an empty list.

Here we have un sorted set of numbers.

```>>> assorted = {4,3,3,5,6,7,8,19,2,0,33}
>>> assorted
{0, 33, 2, 3, 4, 5, 6, 7, 8, 19}```

Now get a copy of the sorted set

```>>> sorted(assorted)
[0, 2, 3, 4, 5, 6, 7, 8, 19, 33]```

#check the original set is not changed, as sorted() returns a copy of sorted set.

```>>> assorted
{0, 33, 2, 3, 4, 5, 6, 7, 8, 19}```

## set operations and set methods.

We have multiple set operation to cover,

Lets consider two sets a, b as below.

```>>> a = {1,2,3,4}
>>> b = {10, 9,5,2,7,5,3,6}```
```>>> a
{1, 2, 3, 4}
>>> b
{2, 3, 5, 6, 7, 9, 10}

```

### set() is mutable collection

#1. Add an element to set

Adds an element to the set.

If the object already present in the set nothing happens.

Ex 1.

```>>> a.add(5)
>>> a
{1, 2, 3, 4, 5}```

Ex 2.

```#trying to add 5 again
>>> a
{1, 2, 3, 4, 5}

```

### remove(elem)

If elem is present in the set, removes it from the set.
raises a KeyError otherwise.

```>>> a.remove(3)
>>> a
{1, 2, 4}```

If you try to remove the element which is not present a KeyError is raised.

Lets try to remove element 3, which we have already removed above.

`>>> a.remove(3)`

ouput:

```Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 3```

Removes the elem from the list,if present. Otherwise does nothing.

Similar to remove(), but doesn’t raise error if the element is not present.

a = {1, 2, 3, 4}

#discard element 3 from the set.

`>> a.discard(3)`

#check the contents

```>>> a
{1, 2, 4}```

#try again to discard the element which is not present

`>> a.discard(3)`

Notice nothing happens.

### clear()

Removes all the elements from the list.
if set is empty does nothing.

a = {1, 2, 3, 4}

`>>> a.clear()`

#check the contents of the set, it should be an empty set.

```>>> a

set()

```

Set in Python is similar to mathematical set,

we can do all set operation like in maths.

Few examples are as below.

### union of sets

Union of sets contains all the elements of sets.

‘|’ pipe symbol is used to get union.

```>>> a = {1,2,3,4}
>>> b = {10, 9,5,2,7,5,3,6}```

```>>> a | b
{1, 2, 3, 4, 5, 6, 7, 9, 10}
>>>```

We can use set method union to get a union of sets.

### union(set)

Same as a | b.

a.union(b)

```>>> a.union(b)
{1, 2, 3, 4, 5, 6, 7, 9, 10}

```

### intersection of sets

Intersection is a set containing common elements of both sets.

‘&’ symbol is used to get intersection.

```>>> a & b
{2, 3}

>>> b & a
{2, 3}

```

set method intersection() gives the same result as below

### intersection(set)

```>>> a.intersection(b)
{2, 3}

>>> b.intersection(a)
{2, 3}

```

### difference of sets.

Difference set contains, left-hand set with all elements from the right-hand
set removed.

‘-‘ is used to difference of sets.

```>>> a
{1, 2, 3, 4}

>>> b
{2, 3, 5, 6, 7, 9, 10}

>>> a -b
{1, 4}

>>> b - a
{5, 6, 7, 9, 10}

```

### symmetric difference.

The resulting set has elements which are unique to each set

‘^’ is get the symmetric difference.

```>>> a ^ b
{1, 4, 5, 6, 7, 9, 10}

>>> b ^ a
{1, 4, 5, 6, 7, 9, 10}

```

### copy()

Returns a shallow copy of a set.

```>>> a = {1,2,3,4}
>>> c = a.copy()

>>> c
{1, 2, 3, 4}

```

### issubset(superset)

Returns True if the set is subset of super-set, otherwise False.

we  have two sets here a and ss.

```>>> a = {1,2,3,4}

>>> ss = {2,3}

>>> ss.issubset(a)
True

```

another set ss1 which contains different elements.

```>>> ss1 = {6,7}

>>> ss1.issubset(a)
False

```

### issuperset(subset)

Returns True if the set is super-set of subset, otherwise False.

```>>> a.issuperset(ss)
True

>>> a.issuperset(ss1)
False

```

### Set Comparison Operators

All of the standard comparisons (‘<’, ‘<=’, ‘>’, ‘>=’, ‘==’, ‘!=’, in, not in) work with sets.

## FROZENSET

### What is a forzenset ?

frozenset is an immutable set.

Like set Its an un-ordered collection of unique elements.

As frozenset is immutable, we cannot add, modify or delete elements.

### How to create a frozenset ?

frozenset is created by using a frozenset() built-in funciton.

Create an empty frozenset.

fs = frozenset()

#check the type

>>> type(fs)
<class ‘frozenset’>

Like set we can create frozenset from an iterable object.

### creating a frozenset form an iterable object.

Ex 1:

```#creating frozenset from tuple
fs1 = frozenset((0,1,1,2,3,2,3,4,5))

>>> fs1
frozenset({0, 1, 2, 3, 4, 5})```

Ex 2:

```#creating frozenset from list
>>> nums = [0,1,1,2,3,2,3,4,5]
>>> fs1 = frozenset(nums)
>>> fs1
frozenset({0, 1, 2, 3, 4, 5})```