Set

Set – Data Structure in Python

In Python, a set is a built-in data structure that represents an unordered collection of unique elements. Sets are similar to lists and tuples, but with the key difference that they do not allow duplicate elements.

Sets are defined using curly braces {}, with each element separated by a comma. Alternatively, we can create a set from a list or tuple using the set() constructor. For example:

pythonCopy codemy_set = {1, 2, 3, 4, 5}
my_set = set([1, 2, 3, 4, 5])

We can add elements to a set using the add() method:

pythonCopy codemy_set.add(6)

We can also remove elements from a set using the remove() method:

pythonCopy codemy_set.remove(2)

We can perform various set operations, such as union, intersection, and difference, using the corresponding methods or operators. For example:

pythonCopy codeset1 = {1, 2, 3}
set2 = {2, 3, 4}
union = set1.union(set2)
intersection = set1.intersection(set2)
difference = set1.difference(set2)

Overall, sets are a useful data structure in Python when we want to store a collection of unique elements and perform set operations efficiently. They are commonly used in many programming tasks, such as data processing and machine learning.

Apply for Python Certification!

https://www.vskills.in/certification/certified-python-developer

Back to Tutorials

Share this post
[social_warfare]
Sequences
VTP Pruning

Get industry recognized certification – Contact us

keyboard_arrow_up