Python set() function

Python set() is used to create a set from iterable.As set does not allow duplicate, set function will retain only unique elements and will remove duplicates.It is one of the way to create set.


iterable(optional): Iterable is optional parameter which can be iterable(list etc) or iterable object.
If iterable is not passed, set() will create empty set.


It returns the set .


Let’s see a very simple example:

s=set() print("Emply set:",s) s1=set([1,4,5,6,4,3,2,3,4,4]) print("Set created from list:",s1) s2=set({'x':1,'y':2}) print("Set created from dictionary:",s2) s3=set(range(5)) print("set created from range function:",l3) s4=set('apple') print("set created from string:",s4)


Emply set: set()
Set created from list: {1, 2, 3, 4, 5, 6}
Set created from dictionary: {‘y’, ‘x’}
set created from range function: [0, 1, 2, 3, 4]
set created from string: {‘e’, ‘p’, ‘a’, ‘l’}

As you can see, when you apply set function, it removes all duplicate elements from the iterable.
That’s all about Python set() function.

Leave a Reply

Your email address will not be published. Required fields are marked *