Python 3-Set

Python Set

A Set is an unordered collection of items. Every elements should be unique and immutable. Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc.

Representation -> {}

The difference between Dictionary and Set is,

  • Dictionary holds key-value pairs
  • Set data type holds only unique keys

Accessing an element from the set:

We cannot use the indexing concept in set because set elements are unordered. But the for loop is used to iterate the existing values in set.

Example:

>>> a={10,20,30,40,50}
>>> a
{40, 10, 50, 20, 30}
>>> for i in a:
...     print(i)
...
40
10
50
20
30
>>>

Look at the above example, the values are unordered in the set.

Set Add:

Add operation in set is carried out by two different functions namely,

Add() -> add one element to the set element

Update() -> add more than one element to the set element

Examples:

>>> a
{40, 10, 50, 20, 30}
>>> a.add(60)
>>> a
{40, 10, 50, 20, 60, 30}
>>> a.update(['ten',100])
>>> a
{100, 40, 10, 't', 50, 20, 'e', 'ten', 'n', 60, 30}
>>> a.update(['tens',1000],['hundereds',100])
>>> a
{100, 40, 1000, 10, 't', 'hundereds', 50, 20, 'e', 'ten', 'n', 60, 'tens', 30}
>>>

Deleting an element from a set:

There are two methods to delete an element from a set, either we can use remove or discard method of set object. To remove the random element from a set, we use pop() function. Also we can use the clear keyword to delete the whole set.

Examples:

>>> a
{100, 40, 1000, 10, 't', 'hundereds', 50, 20, 'e', 'ten', 'n', 60, 'tens', 30}
>>> a.remove(1000)
>>> a
{100, 40, 10, 't', 'hundereds', 50, 20, 'e', 'ten', 'n', 60, 'tens', 30}
>>> a.discard('t')
>>> a
{100, 40, 10, 'hundereds', 50, 20, 'e', 'ten', 'n', 60, 'tens', 30}
>>> a.pop()
100
>>> a.pop()
40
>>> a
{10, 'hundereds', 50, 20, 'e', 'ten', 'n', 60, 'tens', 30}
>>> a.clear()
>>> a
set()
>>>