Skip to main content

Python: Sets

Set is an unordered collection of items. Each element in the set must be unique. Sets remove the duplicate elements. Sets are mutable which means we can modify it after its creation.

The order of elements in a set is undefined though it may consist of various elements. It can also be used to perform mathematical set operations like union, intersection, symmetric difference, etc.

Creating a set

A set can be created in two ways:

By using curly braces:

It  is created by placing all the items (elements) inside curly braces {}, separated by comma.

set_1 = {'a','b','c','d'}
print(set_1)

Output: {'c', 'd', 'a', 'b'}

Note: Insertion order is not maintained.

By using set() method

set() method is an in-built function.

set_1 = set({'a','b','c','d'})
print(set_1)
print(type(set_1))

Output:

{'a', 'c', 'd', 'b'}
<class 'set'>
Tags
Submitted by devanshi.srivastava on June 18, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.