Python Set Operations – Python Tutorial

6 months ago Lalit Bhagtani 0

Python Set Operations : In this tutorial, we will learn about different python set operations, some of them are as follows :

  1. Set Contains
  2. Set Not Contains
  3. Set Length
  4. Set Deletion
  5. Set Min & Max

Python Set Operations

Set Contains

Operator in can be used to check, if a given element is present in the set or not. If a element is present in the set then return True otherwise return False.

# create set object and assign it to variable s s = {1,2,3,4,5} # example of contains contains = 1 in s print(contains) contains = 6 in s print(contains)

Set Not Contains

Operator not in can be used to check, if a given element is present in the set or not. If a element is present in the set then return False otherwise return True.

# create set object and assign it to variable s s = {1,2,3,4,5} # example of not contains not_contain = 1 not in s print(not_contain) not_contain = 6 not in s print(not_contain)

Set Length

Python’s len() function can be used to get the length of a set.

Syntax: len(< Set Object >)

For example:

# create set object and assign it to variable s s = {1,2,3,4,5,5,6,6} # call len() method to get length of the set s length = len(s) # print the value of variable length print(length)

Set Deletion

We can use del statement to delete set object entirely. For example:

# create set object and assign it to variable s s = {'Jan','Feb','Mar'} # print set s print(s) # delete set s del s # print set s print(s)

Set Min & Max

Python’s min() and max()  function can be used to get minimum and maximum element in the set.

Syntax: min(< Set Object >)

               max(< Set Object >)

For example:

# create set object and assign it to variable s s = {1,2,3,4,5} # call min() method to get minimum element in the set s minimum = min(s) # print the value of variable minimum print(minimum) # call max() method to get maximum element in the ser s maximum = max(s) # print the value of variable maximum print(maximum)

References :-

  1. Set Docs

That’s all for Python Set Operations. If you liked it, please share your thoughts in comments section and share it with others too.
Previous