Sets in Python

What is sets?

A set is a collection of unordered and unique elements. They are used to store multiple elements like list and tuple. But set are (unordered ,unchangeable and unindexed) set are denoted by curly brackets {}

1). How to Create set ?

In Python, you can create a set using curly brackets {} or the built-in set() function.

For Example:

a = {2,3,4,False,"technology e blogs"}
print(a)

Output is : {2,3,4,False,"technology e blogs"}

2). Create empty set:

If you want to create an empty set then you use built-in set() function

Note You cannot create an empty set by using curly brackets{} because python default it consider dictionary. So you can use set() function to create empty sets.

For Example:

( Wrong ) Method:

a = {}
print(type(a))

Output is : <class 'dict'>

( Correct ) Method:

a = {}
print(type(a))

Output is : <class 'set'>

3). Add Elements in set:

You can add elements to a set in Python by using the update() and add()  method

Note: If you want to add single element in set then you can use add() method.

For Example:

a = {1,2}
a.add(4)
print(a)

Output is : {1, 2, 4}

Note: If you want to add multiple elements in set then you can use update() method.

For Example:

a = {1,2}
a.update([4,3])
print(a)

Output is : {1, 2, 3, 4}

4). Remove element from Set:

You can remove element from set so you have considered three methods like remove(), discard() and pop() method.

For Example:

i). remove() Method:

a = {1,2,"Apple","Graphs"}
a.remove("Graphs")
print(a)

Output is : {1, 2, 'Apple'}

Note: remove() method removes the specified element from the set. If the element is not present in the set, then it will raise a Error exception.

ii). discard() Method:

a = {1,2,"Apple","Graphs"}
a.discard("Graphs")
print(a)

Output is : {1, 2, 'Apple'}

Note: discard() method also removes the specified element from the set. but, if the element is not present in the set, then it will not raise an exceptional Error.

iii). pop() Method:

a = {1,2,"Apple","Graphs"}
a.pop()
print(a)

Output is : {2, 'Apple', 'Graphs'}

Note: pop() method removes an arbitrary element from the set and returns it. If the set is empty, it will raise an Error exception. 

Note: Sets are unordered, the element removed by pop() is not necessarily the first or last element of the set.

PYTHON COMPLETE COURSE IN HINDI ðŸ‘ˆðŸ’ª

LIKE | SHARE and SUBSCRIBE 👇👇👇