Set in Python

Published: 07 February 2022
on channel: Parag Dhawan
585
7

In Python, a set is an unordered collection of unique elements. It is similar to a list or a tuple, but unlike lists and tuples, sets cannot contain duplicate elements. Sets are mutable, which means you can add or remove elements from a set.

To create a set in Python, you can use the set() function or use curly braces {} to enclose a list of elements:

Creating a set using the set() function
set1 = set([1, 2, 3, 4])

Creating a set using curly braces {}
set2 = {4, 5, 6, 7}
You can add elements to a set using the add() method, and remove elements using the remove() method:

Adding an element to a set
set1.add(5)

Removing an element from a set
set2.remove(7)

You can perform set operations such as union, intersection, difference, and symmetric difference using built-in methods such as union(), intersection(), difference(), and symmetric_difference():

Union of two sets
set3 = set1.union(set2)

Intersection of two sets
set4 = set1.intersection(set2)

Difference of two sets
set5 = set1.difference(set2)

Symmetric difference of two sets
set6 = set1.symmetric_difference(set2)

You can also check if a set is a subset or a superset of another set using the issubset() and issuperset() methods:

Checking if a set is a subset of another set
set7 = {1, 2}
subset = set7.issubset(set1)

Checking if a set is a superset of another set
superset = set1.issuperset(set7)

Overall, sets are a powerful data structure in Python that can be used to perform various set operations such as union, intersection, difference, and symmetric difference. Sets are particularly useful for dealing with large collections of unique elements, and they can help to simplify and optimize your code.

Set is unordered and unindexed collection of elements enclosed with {}.
Duplicates are not allowed in set.
‪@ParagDhawan‬
#python
#python3
#pythonprogramming
#pythondatastructureset
#set
#pythonset
#paragdhawan


Watch video Set in Python online without registration, duration hours minute second in high quality. This video was added by user Parag Dhawan 07 February 2022, don't forget to share it with your friends and acquaintances, it has been viewed on our site 58 once and liked it people.