DEV Community

Cover image for Sets - Python
datatoinfinity
datatoinfinity

Posted on

Sets - Python

Set is a built-in data type that represents an unordered collection of unique elements. Sets are mutable, means you can add or remove elements after they are created.

In here unordered collection meaning it doesn't maintain any order. For example:

my_set={'Cherry','Banana','Apple'}
print(my_set)
Output
{'Banana', 'Cherry', 'Apple'}

As you can see I have given different order and the output is in different order.

No duplicate value, if we have duplicate in set it will remove it from output.

my_set={1,2,3,4,5,1,2,3}
print(my_set)
Output:
{1, 2, 3, 4, 5}

1. Adding

add()

my_set={1,2,3,4,5}
my_set.add(6)
print(my_set)
Output:
{1, 2, 3, 4, 5, 6}

update()

my_set={1,2,3,4,5}
my_set.update([6,7,8])
print(my_set)

Updated with list

Output:
{1, 2, 3, 4, 5, 6, 7, 8}

And we can also add list and set to update main set.

my_set={1,2,3,4,5}
s2={10,6,7}
my_set.update([6,7,8],s2)
print(my_set)
{1, 2, 3, 4, 5, 6, 7, 8, 10}

2. Removing

my_set={1,2,3,4,5}
my_set.remove(6)
print(my_set)
Output:
ERROR!
Traceback (most recent call last):
  File "", line 2, in 
KeyError: 6

You see '6' is not present in here so remove() showing key error. But if you use discard() function.

my_set={1,2,3,4,5}
my_set.discard(6)
print(my_set)
{1, 2, 3, 4, 5}

3. Set Operation

Intersection

my_set1={1,2,3,4,5}
my_set2={3,4,7,8}
s3=my_set1.intersection(my_set2)
print(s3)
{3, 4}

It took only those value which both set have.

Difference

my_set1={1,2,3,4,5}
my_set2={3,4,7,8}
s3=my_set1.difference(my_set2)
print(s3)
{1, 2, 5}

As you see it only give output for my_set1 only and only those elements which not present in my_set2.

Symmetric_difference

my_set1={1,2,3,4,5}
my_set2={3,4,7,8}
s3=my_set1.symmetric_difference(my_set2)
print(s3)
Output:
{1, 2, 5, 7, 8}

It is opposite of difference, it return those value which are not present in both the set.

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.