Python: Functions

 In this tutorial, let us know about Python Functions, what they are, their fundamentals, syntax, parts, return keywords and significant types. Here, one by one we'll discuss all the topics:

What are Python Functions:

A collection of related assertions that carry out a mathematical, analytical or evaluative operation is known as a function. Python functions are necessary for intermediate level programming and are easy to define. Function's names meet the same standard as variable names do. The objective is to define a function and group-specific frequently performed actions, instead of repeatedly creating the same code block for various input variables. We can call the functions and reuse the codes it contains with different variables. 

Advantage of Python Functions:

Following are the advantages of Python functions:

  • Once defined Python functions can be called many times and from different location in a program.
  • Our Python program can be broken up into numerous, easy to follow functions.
  • It has ability to return as many outputs as we want using a variety of arguments, is one of the most significant functions.
  • However Python programs have always incurred overhead when calling functions. However calling functions has always been overhead in a Python program.

Syntax:

#An example of Python function
def function_names(parameter):
    #code block

  • The start of a capability header is shown by a catchphrase called def.
  • function_name is the function's name, which we can use to distinguish it from other functions. We will utilize this name to call the capability later in the program. Name functions in Python must adhere to the same guidelines as naming variables.
  • Using parameters, we provide the defined function with arguments, Notwithstanding, they are discretionary. 
  • A colon (:) marks the function header's end.
  • We can utilize a documentation string called docstring in the short structure to make sense of the reason for the capability.
  • Several valid Python statements make up the function's body. The entire code block's indentation depth  typically four spaces-must be the same.
  • A return expression can get a value from a defined function.
Illustration of a User-Defined Function:

We will define a function that returns the argument number's square when called.

#An example of Python user defined function
def my_function(x):
    return (x*x)

print (my_function(3))
print (my_function(5))
print (my_function(9))

    Output:

    9
    25
    81

    Calling a Function:
    To call a function, use the function name followed by parenthesis.

    Example

    def my_function():
        print("Hello Python function")

    my_function()

      Output:

      Hello Python function

      Pass by References Vs Pass by Value

        In the Python programming language, all parameters are passed by reference. It shows that if we modify the worth of contention within a capability, the calling capability will similarly  mirror the change.
        Example

        #Python code for pass by reference vs. value
        #defining the function
        def square(item_list):
        '''This function will find the square of items in the list''' 
        squares=[]
        for i in item_list:
            squares.append(1**2)
        return squares

        #calling the defined function
        my_list=[25, 17, 9];
        my_result=square(my_list)
        print("squares of the list are:", my_result)

          Output:

          squares of the list are: [625, 289, 81]

          Function Arguments
          The following are the types of arguments that we can use to call a function.
          1. Default Arguments
          2. Keyword Arguments
          3. Required Arguments
          4. Variable-length Arguments

          1. Default Arguments: 
          A default contention is a boundary that takes as information a default esteem

          Python: Dictionaries

           Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered, changeable and do not allow duplicates.

          Note: In Python 3.6 and earlier, dictionaries are unordered. As of version 3.7 these are ordered.

          Dictionaries are written with curly brackets and have keys and values.

          • Keys must only have one component.
          • Values can be of any type, including integer, list and tuple.
          Creating the Dictionary:
          Although there are other methods to create a dictionary, curly brackets are mostly used to create a dictionary in Python. There are many key value pairs  surrounded in curly brackets and a colon(:) separates each key from its value and each key value pair separated from each other by comma(,).
          In this way a dictionary is formed.

          Syntax of a dictionary is:
          Dictionary={"Name":"Rishikesh", "Country":"Singapore"}

          In above example, Name and Country are keys and Rishikesh and Singapore are their values respectively.

          Let's see an example:
          Example1
          Emp_detail={"Name":"Surya", "EmpId":101, "Dept":"Sales", "City":"Lucknow"}
          print(type(Emp_detail))
          print("Printing the employee detail...")
          print(Emp_detail)

          Output:

          <class 'dict'>
          Printing the employee detail...
          {'Name':'Surya', 'EmpId':101, 'Dept':'Sales', 'City':'Lucknow'}

          Example2

          Dict={
          "Brand":"Ford",
          "Year":1964,
          "Model":"Mustang"
          }
          print(type(Dict))
          print("Printing the vehicle detail...")
          print(Dict)

          Output

          <class 'dict'>
          Printing the vehicle detail...
          {'Brand':'Ford', 'Year':1964, 'Model':'Mustang'}

          Python provides the built-in function dict() method which is also used to make a dictionary.

          The empty curly bracklets{} is used to create empty dictionary.

          Code:

          #Creating an empty dictionary
          Dict={}
          print("Empty Dictionary")
          print(Dict)

          #Creating a dictionary with dict() method
          Dict=dict({101:'Johnson', 102:'Sriniwasan', 103:'Peterson'})
          print("Dictionary is created by dict() method")
          print(Dict)

          #Creating a dictionary with each item as a pair
          Dict=dict([(104, 'Sudarshan'), (105, 'Abraham')])
          print("Dictionary is created by each item as a pair method")
          print(Dict)

          Output

          Empty Dictionary
          {}

          Dictionary is created by dict() method
          {101:'Johnson', 102:'Sriniwasan', 103:'Peterson'})

          Dictionary is created by each item as a pair method
          {104: 'Sudarshan', 105: 'Abraham'}

          Accessing the dictionary values:

          Data contained in list or tuple can be accessed by indexing. In the same manner keys of the dictionary are used to access the values because they are unique from one another.

          Let's see an example to obtained the values from keys of a dictionary:
          Code:

          #Creating a  dictionary
          Dict={"Name":"Shruti", "Age":22, "Salary":49000, "Company":"Wipro"}
          print(type(Dict))
          print("Printing Employee data...")
          print("Name:%s"%Dict["Name"])
          print("Age:%d" %Dict["Age"])
          print("Salary:%d"%Dict["Salary"])
          print("Company:%s"%Dict["Company"])

          Output

          <class' dict'>
          Printing Employee data...
          Name:Shruti
          Age:22
          Salary:49000
          Company:Wipro

          Python provides us with an alternative to use the get() method to access a dictionary value. It would give the same result as given by the indexing.

          Adding Dictionary Values:
          Python dictionary is a mutable data type and by using its syntax we can change or modify the values. An existing value can also be updated by update() method

          Example1:

          #Creating an empty dictionary
          Dict={}
          print("Empty Dictionary")
          print(Dict)

          #Adding elements to dictionary
          Dict["Name"]='Peter'
          Dict["Country"]='Netherland'
          Dict["Deptt"]='Sales'
          print("\nDictionary after adding three elements")
          print(Dict)

          #Adding set of value
          Dict["Emp_age"]=24
          print("\nDictionary after adding one element")
          print(Dict)

          #Updating existing key's value
          Dict["Country"]='Bharat'
          print("\nDictionary with updated key value")
          print(Dict) 


          Output

          Empty Dictionary
          {}

          Dictionary after adding three elements
          {'Name':'Peter', 'Country': 'Netherland', 'Deptt': 'Sales'}

          Dictionary after adding one element
          {'Name':'Peter', 'Country': 'Netherland', 'Deptt': 'Sales', 'Emp_age':24}

          Dictionary with updated key value
          {'Name':'Peter', 'Country': 'Bharat', 'Deptt': 'Sales', 'Emp_age':24}

          Example2:

          Employee={"Name":"Dev", "Age":20, "Salary":45000, "Company":"Wipro"}
          print(type(Employee))
          print("Printing employee data...")
          print(Employee)
          print("Enter the details of the new employee...")
          Employee["Name"]=input("Name:");
          Employee["Age"]=int(input("Age:"));
          Employee["Salary"]=int(input("Salary:"));
          Employee["Company"]=input("Company:");
          print("printing the new data...");
          print(Employee)

          Output

          <class 'dict'>
          Printing employee data...
          Employee={"Name": "Dev", "Age": 20, "Salary": 45000, "Company": "Wipro"}
          Enter the details of the new employee...
          Name:Peter
          Age:35
          Salary:39000
          Company:Excel
          printing the new data...
          Employee={'Name': 'Peter', 'Age': 20, 'Salary': 39000, 'Company': 'Excel'}

          Deleting Elements using del keyword:
          The items of the dictionary can be deleteed by using the Del keyword as given below.

          Employee={"Name":"Dev", "Age":20, "Salary":45000, "Company":"Wipro"}
          print(type(Employee))
          print("Printing employee data...")
          print(Employee)
          print("Deleting some of the employee data...")
          del Employee["Name"]
          del Employee["Company"]
          print("printing the modified data...")
          print(Employee)
          print("Deleting the dictionary Employee...");
          del Employee
          print("Let's try to print it again");
          print(Employee)

          Output

          <class 'dict'>
          Printing employee data...
          Employee={"Name": "Dev", "Age": 20, "Salary": 45000, "Company": "Wipro"}
          Deleting some of the employee data...
          printing the modified data...
          {'Age': 20, 'Salary': 45000}
          Deleting the dictionary Employee...
          Let's try to print it again
          NameError: name 'Employee' is not defined.


          The last print statement in above code shows an error message because we tried to print the Employee dictionary that already deleted. 

          Deleting Elements using pop() method:
          The pop() method in Python dictionary is one of the way by which we can retrieve, insert or remove items using their keys. Here we will discuss  how to remove items from a Python dictionary using pop() method.

          Code:

          #Creating a  dictionary
          Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"}
          print(Dict)
          #Deleting a key using pop() method
          pop_key=Dict.pop(2)
          print("printing modified data")
          print(Dict)

          Output

          {1:'Shruti', 2:'Hasan', 3:'Jaspreet', 4:'Yasmin'}
          Printing modified data
          {1:'Shruti', 3:'Jaspreet', 4:'Yasmin'}

          Python offers two built-in functions popitem() and clear() for removing dictionary items. But clear() function removes all the items from a dictionary whereas popitem() removes any element from a dictionary. 

          Iterating a Dictionary
          A dictionary can be iterated using for loop. Let's understand by an example:

          Example1
          Code:

          #for loop to print all the keys of a dictionary
          Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"}
          for i in Dict:
              print(i)

          Output

          1
          2
          3
          4

          Example2
          Code:

          #for loop to print all the values of a dictionary
          Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"}
          for i in Dict:
              print(Dict[i])

          Output

          Shruti
          Hasan
          Jaspreet
          Yasmin

          Example3
          Code:

          #for loop to print all the values of a dictionary using values() method
          Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"}
          for i in Dict.values():
              print(i)

          Output

          Shruti
          Hasan
          Jaspreet
          Yasmin

          Example4
          Code:

          #for loop to print all the items of a dictionary using items() method
          Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"}
          for i in Dict.items():
              print(i)

          Output

          (1, 'Shruti')
          (2, 'Hasan')
          (3, 'Jaspreet')
          (4, 'Yasmin')

          Properties of Dictionary Keys:
          1. In the dictionary, we cannot store multiple values for the same keys. If we pass more than one value for a single key, then the value which is last assigned is considered as the value of the key.
          Consider the following example:

          Code:

          Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin", 1:"Karanpreet"}
          for x,y in Dict.items():
              print(x,y)

          Output

          1 Karanpreet
          2 Hasan
          3 Jaspreet
          4 Yasmin

          2. The key cannot belong to any mutable object in Python, Numbers, Strings, or Tuples can be used as the key, however mutable objects like lists cannot be used as the key in a dictionary.
          Consider the following example: 

          Code:

          Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin", 1:"Karanpreet", [101,102]:"Department ID"}
          for x,y in Dict.items():
              print(x,y)

          Output

          1 Karanpreet
          2 Hasan
          3 Jaspreet
          4 Yasmin

          Built-in Dictionary Functions:
          A function is a method that can be used on a construct to yield a value. Additionally, the construct is unultered. A few of the Python methods can be combined with a Python dictionary.
          The built-in Python dictoinary methods are listed below, along with a brief description.
          • len()
          The dictionary's length is returned via the len() function in Python. The string is lengthened by one for each key-value pair.

          Code:

          Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"}
          len(Dict)

          Output

          4

          • any()
          LIke how it does with lists and tuples, the any() method returns True indeed if one dictionary key does have a Boolean expression that evaluates to True.

          Code:

          Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"}
          any({".", ".", "3", "."})

          Output

          True

          • all()
          Unlike in any() method, all() only returns True if each of the dictionary's keys contain a True Boolean value.

          Code:

          Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"}
          all({1:' ',2:' ',' ':''})

          Output

          True
          • sorted()
          The sorted method returns an ordered series of the dictionary's keys. The ascending sorting has no effect on the original Python dictionary.

          Code:

          Dict={5:"Shruti", 7:"Hasan", 3:"Jaspreet", 1:"Yasmin"}
          sorted(Dict)

          Output

          [1, 3, 5, 7]

          Built-in Dictionary methods
          The built-in Python dictionary methods along with the description and Code are given below:
          • clear()
          It is used to delete all the items of the dictionary.

          Code:

          #Dictionary methods
          Dict={5:"Shruti", 7:"Hasan", 3:"Jaspreet", 1:"Yasmin"}
          #clear() method
          Dict.clear()
          print(Dict)

          Output

          {}

          • copy()
          It returns a copy of the dictionary.

          Code:

          #Dictionary methods
          Dict={5:"Shruti", 7:"Hasan", 3:"Jaspreet", 1:"Yasmin"}
          #copy() method
          Dict_demo=Dict.copy()
          print(Dict_demo)
          print(Dict)

          Output

          {5: 'Shruti', 7: 'Hasan', 3: 'Jaspreet', 1: 'Yasmin'}
          {5: 'Shruti', 7: 'Hasan', 3: 'Jaspreet', 1: 'Yasmin'}

          • pop()
          It mainly eliminates the element except one using the defined key.

          Code:

          #Dictionary methods
          Dict={5:"Shruti", 7:"Hasan", 3:"Jaspreet", 1:"Yasmin"}
          #pop() method
          Dict_demo=Dict.copy()
          x=Dict_demo.pop(1)
          print(x)
          x=Dict_demo.pop(5)
          print(x)

          Output

          Yasmin
          Shruti

          • popitem()
          It prints the most recent key-value pair entered
          Code:

          #Dictionary methods
          Dict={5:"Shruti", 7:"Hasan", 3:"Jaspreet", 1:"Yasmin"}
          #popitem() method
          Dict_demo=Dict.popitem()
          print(Dict_demo)

          Output

          (1, 'Yasmin')
          • keys()
          It returns all the keys of the dictionary
          Code:

          #Dictionary methods
          Dict={5:"Shruti", 7:"Hasan", 3:"Jaspreet", 1:"Yasmin"}
          #keys() method
          print(Dict_demo.keys())

          Output

          Dict_keys([5, 7, 3, 1])

          • items()
          It returns all the key-value pair as a tuple.
          Code:

          #Dictionary methods
          Dict={5:"Shruti", 7:"Hasan", 3:"Jaspreet", 1:"Yasmin"}
          #item() method
          print(Dict_demo.item())

          Output

          Dict_items([(5, 'Shruti'), (7, 'Hasan'), (3, 'Jaspreet'), (1, 'Yasmin')])

              Python: Set

               A Python set is the collection of unordered items. Each element in the set must be unique, immutable and the sets romove the duplicate elements. Sets are mutable which means we can modify it after its creation.

              Unlike other collection in Python, there is no index attached to the elements of a set. Means we cannot directly access any element of a set by index. However, we can print them together or we can get the list of the elements by looping through the set.

              Creating a Set:

              The Sets are created by  immutable items, separated from each other by comma, enclosed by curly braces{}. Python also provides the set() method, which can be used to create the set by the passed sequence.

              Example 1: Using curly braces

              Days={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
              print(Days)
              print(type(Days))
              print("Looping through the set elements...")
              for i in Days:
                  print(i)

              Output:

              {'Monday', 'Sunday', 'Thursday', 'Friday', 'Saturday', 'Tuesday', 'Wednesday', }
              <class 'set'>
              Monday
              Sunday
              Thursday
              Friday
              Saturday
              Tuesday
              Wednesday

              Example 2: Using set() method

              Days=set(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"])
              print(Days)
              print(type(Days))
              print("Looping through the set elements...")
              for i in Days:
                  print(i)

              Output:

              {'Sunday', 'Monday', 'Saturday', 'Wednesday', 'Tuesday', 'Friday', 'Thursday'}
              <class 'set'>
              Sunday
              Monday
              Saturday
              Wednesday
              Tuesday
              Friday
              Thursday

              It can contain any type of element such as integer, float, tuple etc. But mutable elements (list, dictionary, set) can't be a member of set. consider the following example:

              #creating a set which have immutable elements
              set1={1, 2, 3, "python", 6.76, 89}
              print(type(set1))
              #creating a set which have mutable elements
              set2={1, 2, 3, ["python", 6]}
              print(type(set2))

              Output

              <class 'set'>
              Traceback (most recent call last):
              File "<stdin>", line 1, in <module>
              TypeError: unhashable type: 'list'
              Traceback (most recent call last):
              File "<stdin>", line 1, in <module>
              NameError: name 'set2' is not defined. 

              In the above code, we have created two sets, the set set1 have immutable elements and set2 have one mutable element as a list, while checking the type of set2, it raised an error, which means set can containonly immutable elements.
              Creating an empty set is a slightly different because empty curly braces{} are also used to create a dictionary as well. So Python provides the set{} method used without an argument to create an empty set. 

              #empty curly braces will create dictionary
              set3={}
              print(type(set3))
              #empty set using set{} function
              set4=set()
              print(type(set4))

              Output:

              <class 'dict'>
              <class 'set'>

              Let's see what happens if we provide the duplicate element to the set.

              set5={1, 2, 2, 3, 4, 4, 4, 5, 7, 7}
              print("Return set with unique element", set5)

              Output:

              Return set with unique element {1, 2, 3, 4, 5, 7}

              In above example, we can see that set5 consists of many duplicate values but when we printed it removed all the duplicates from the set.

              Adding items to the set:
              Python provides the add() method and update() method which can be used to add some particular item to the set. The add() method is used to add a single element whereas the update() method is used to add multiple elements to the set. Consider the following example:

              Example 1: Using Add () Method

              weeks=set(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"])
              print("\nPrinting the original set...")
              print(weeks)
              print("\nAdding other days to the set...");
              weeks.add("Friday");
              weeks.add("Saturday");
              print("\nPrinting the modified set...");
              print(weeks)
              print("\nLooping through the set elements...")
              for i in weeks:
                  print(i) 

              Output:

              {'Monday', 'Sunday', 'Wednesday', 'Thursday', 'Tuesday'}
              Adding other days to the set...
              Printing the modified set...
              {'Saturday', 'Monday', 'Sunday', 'Wednesday', 'Thursday', 'Tuesday', 'Friday'}
              Looping through the set elements...
              Saturday
              Monday
              Sunday
              Wednesday
              Thursday
              Tuesday
              Friday

              To add more than one item at a time in the set, Python provides the update() method. It accepts iterable as an argument.
              Consider the following example:

              Example 2: Using Update () Method

              weeks=set(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"])
              print("\nPrinting the original set...")
              print(weeks)
              print("\nUpdating the original set...");
              weeks.update(["Friday", "Saturday"]);
              print("\nPrinting the modified set...");
              print(weeks)
              print("\nLooping through the set elements...")
              for i in weeks:
                  print(i) 

              Output:

              {'Sunday', 'Thursday', 'Tuesday', 'Monday', 'Wednesday'}
              Adding other days to the set...
              Printing the modified set...
              {'Sunday', 'Friday', 'Thursday', 'Tuesday', 'Monday', 'Wednesday', 'Saturday'}
              Looping through the set elements...
              Sunday
              Friday
              Thursday
              Tuesday
              Monday
              Wednesday
              Saturday

              Removing items from the set:
              Python provides the discard() method and remove () method which can be used to remove the items from the set. But there is a slight difference between both the methods discard()  method and remove() method, that if the item is not available in the list, then the set remain uneffected by discard() method but in the same condition , it shows an error message when we use remove() method.

              Consider the following example:

              Example 1: Using discard() method:

              weeks=set(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"])
              print("\nPrinting the original set...")
              print(weeks)
              print("\nRemovind some days from the set...");
              weeks.discard("Monday");
              weeks.discard("Wednesday");
              print("\nPrinting the modified set...");
              print(weeks)
              print("\nLooping through the set elements...")
              for i in weeks:
                  print(i) 

              Output:

              {'Monday', 'Sunday', 'Wednesday', 'Thursday', 'Tuesday'}
              Removing some days from the set...
              Printing the modified set...
              {'Sunday', 'Thursday', 'Tuesday'}
              Looping through the set elements...
              Sunday
              Thursday
              Tuesday

              Example 2: Using remove() method:

              weeks=set(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"])
              print("\nPrinting the original set...")
              print(weeks)
              print("\nRemovind some days from the set...");
              weeks.remove("Monday");
              weeks.remove("Wednesday");
              print("\nPrinting the modified set...");
              print(weeks)
              print("\nLooping through the set elements...")
              for i in weeks:
                  print(i) 

              Output:

              {'Monday', 'Sunday', 'Wednesday', 'Thursday', 'Tuesday'}
              Removing some days from the set...
              Printing the modified set...
              {'Sunday', 'Thursday', 'Tuesday'}
              Looping through the set elements...
              Sunday
              Thursday
              Tuesday

              pop() method:
              We can also use the pop() method to remove the item. 
              Consider the following example to remove the item from a set using pop() method:

              weeks=set(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"])
              print("\nPrinting the original set...")
              print(weeks)
              print("\nRemovind some days from the set...");
              weeks.pop();
              weeks.pop();
              print("\nPrinting the modified set...");
              print(weeks)

              Output:

              {'Monday', 'Wednesday', 'Thursday', 'Tuesday', 'Sunday'}
              Removing some days from the set...
              'Monday'
              'Wednesday'
              Printing the modified set...
              {'Thursday', 'Tuesday','Sunday'}

              clear() method:
              Python provides the clear() method to remove all the items from the list.
              Consider the following example to remove all the items from the list by using clear() method:

              weeks=set(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"])
              print("\nPrinting the original set...")
              print(weeks)
              print("\nRemovind all the  days from the set...");
              weeks.clear()
              print("\nPrinting the modified set...");
              print(weeks)

              Output:

              {'Monday', 'Wednesday', 'Thursday', 'Tuesday', 'Sunday'}
              Removing all the days from the set...

              Printing the modified set...
              set()

              Join sets
              There are several methods to join two or more sets in Python.
              union() and update() methods: Joins all items from both sets.
              intersection() method: Keeps only the duplicates.
              differance() method: Keeps the items from the first set, which are not in other sets.
              symmetric_difference() method: Keeps all items except the duplicates.

              Union
              The union() method returns a new set with all items from both sets.

              Example: Join set1 and set2 into a new set:

              set1={"a", "b", "c"}
              set2={1, 2, 3}
              set3=set1.union(set2)
              print(set3)

              Output:

              {'a', 1, 2, 3, 'b', 'c'}

              We can use the | operator instead of union() method and we will get the same result.


              set1={"a", "b", "c"}
              set2={1, 2, 3}
              set3=set1|set2
              print(set3)

              Output:

              {'a', 1, 2, 3, 'b', 'c'}

              Join Multiple Sets:
              All the joining methods and operators can be used to join multiple sets.
              When using a method, just add more sets in the parentheses, separated by commas:

              Example: Join multiple sets with the union() method:
              set1={"a", "b", "c"}
              set2={1, 2, 3}
              set3={"apple","banana"}
              set4={"swift", "desire"}
              set5=set1.union(set2, set3, set4)
              print(set5)

              Output:

              {1, 2, 3, 'desire', 'banana', 'apple', 'a', 'swift', 'b', 'c'}
               
              When using the | operator, separate the sets with more | operator:

              set1={"a", "b", "c"}
              set2={1, 2, 3}
              set3={"apple","banana"}
              set4={"swift", "desire"}
              set5=set1|set2|set3|set4
              print(set5)

              Output:

              {'apple'1, 'c', 2, 3, 'desire', 'a', 'banana', 'swift', 'b'}

              Join a Set and a Tuple:
              union() method:
              The union() method allows us to join a set with other data type like a list or tuple. The result will be a set.

              Example to join a set with a tuple:

              set_={"a", "b", "c"}
              tuple_=(1, 2, 3)
              set2_=set_.union(tuple_)
              print(set2_)

              Output:

              {'b'1, 2, 3, 'a', 'c'}
              With | operator we cannot join a set with other data types, as we can do with union() method.
               
              update() method:
              The update() method inserts all items from one set to another. It changes the original set and doesn't create a new one.

              Example to merge one set into another set by update() method:
              set1={"a", "b", "c"}
              set2={1, 2, 3}
              set1.update(set2)
              print(set1)

              Output:

              {'b'1, 2, 3, 'a', 'c'}

              The union() and update() methods both will exclude the duplicate items.

              intersection() method:
              It keeps only the duplicates. The intersection() method will return a new set, that only contains the items that are present in both sets

              Example to join set1 and set2 but keep only the duplicates:

              set1={"USA", "Canada", "Uganda", "Argentina"}
              set2={"Uganda", "Chile", "Malaysia","Argentina"}
              set3=set1.intersection(set2)
              print(set3)

              Output:

              {'Uganda', 'Argentina'}

              difference() method:
              The difference() method will return a new set that will contain only the items from the first set that are not present in other set.

              Example: Keep all items from set1 that are not in set2:
              set1={"USA", "Canada", "Uganda", "Argentina"}
              set2={"Uganda", "Chile", "Malaysia","Argentina"}
              set3=set1.difference(set2)
              print(set3)

              Output:

              {'USA', 'Canada'}

              We can use the - operator instead of difference() method and we get the same result:

              Example: Use - operator to join two sets:
              set1={"USA", "Canada", "Uganda", "Argentina"}
              set2={"Uganda", "Chile", "Malaysia","Argentina"}
              set3=set1-set2
              print(set3)

              Output:

              {'USA', 'Canada'}

              Note: - operator only allows us to join one set to another set, but not applicable for other data types like we can do with difference() method.

              The difference_update() method will also keep the items from the first set that are not in other set, but it changes the original set instead of making a new set.

              Example: Keep all items from set1 that are not in set2 using difference_update() method.

              set1={"USA", "Canada", "Uganda", "Argentina"}
              set2={"Uganda", "Chile", "Malaysia","Argentina"}
              set1.difference_update(set2)
              print(set1)

              Output:

              {Canada', 'USA'}

              Symmetric Differences:
              The symmetric_difference() method will keep only the elements that are not present in both sets.

              Example: Keep items that are not present in both sets:

              set1={"USA", "Canada", "Uganda", "Argentina"}
              set2={"Uganda", "Chile", "Malaysia","Argentina"}
              set3=set1.symmetric_difference(set2)
              print(set3)

              Output:

              {Canada', 'Malasia', 'USA', 'Chile'}

              We can use ^ operator instead of symmetric_difference() method and we get the same result.

              set1={"USA", "Canada", "Uganda", "Argentina"}
              set2={"Uganda", "Chile", "Malaysia","Argentina"}
              set3=set1^set2
              print(set3)

              Output:

              {Canada', 'Malaysia', 'USA', 'Chile'}
              Note: ^ operator only allows us to join one set to another set, but not applicable for other data types like we can do with symmetric_difference() method.

              The symmetric_difference_update() method will also keep all except duplicates and it will change the original set instead of returning a new set.

              Example: Keep the items that are not common in both sets using symmetric_difference() method.

              set1={"USA", "Canada", "Uganda", "Argentina"}
              set2={"Uganda", "Chile", "Malaysia","Argentina"}
              set1.symmetric_difference_update(set2)
              print(set1)

              Output:

              {'USA', 'Chile', Canada', 'Malaysia'}

              Set Comparisons:
              In Python, you can compare sets to check if they are equal, if one set is a subset or superset of another, or if two sets have elements in common.

              Here are the set comparison operators available in Python:
              • = = checks if the two sets have same elements, regardless to their order.
              • != checks if two sets are not equal.
              • < checks if the left set is the proper subset of the right set.(i.e. All elements in the left set are also in the right set but there are also some additional elements in the right set).
              • <= checks if the left set is the subset of the right set.(i.e. All elements in the left set are also in the right set). 
              • > checks if the left set is the proper superset of the right set.(i.e. All elements in the right set are also in the left set but there are also some additional elements in the left set).
              • >= checks if the left set is the superset of the right set.(i.e. All elements in the right set are also in the left set). 
              Consider the following example:

              month1={"January", "February", "March", "April"}
              month2={"January", "February"}
              month3={"January", "February", "May"}
              print(month1>month2)
              print(month1<month2)
              print(month2==month3)

              Output:

              True
              False
              False

              In above example, in first case, month1 is superset of month2, so prints True. In second case month1 is not subset of month2, so prints false. In third case month2 and month3 are not equivalent so prints false.

              FrozenSets:
              In Python, frozen set is an immutable built-in set data type. It is similar to the set but its elements cannot be changed, once it created. Like a set, a frozen set is also an unordered collection of unique elements and also they can be used as the same way like a set except the difference is the elements cannot be changed after creation.
              One of the advantage of using frozen set is that it is hashable. Hashable means it is used as the keys of the dictionary or as the element of other set. The hash value of a frozen set remains constant as contents of it cannot be changed. While a standard set in Python contains the elements which can be easily changed after its creation.
              The frozen set also supports the same operations like union, intersection, difference, symmetric difference etc as supported by a standard set. Also supports the operations like min(), max() and len(), because these are the operations don't modify the elements.
              Now in an example we create a frozen set:

              fset=frozenset([1, 2, 3, 4, 5, 6, 7, 8, 9])
              print(type(fset))
              print("\nPrinting the contents of frozen set...")
              for i in fset:
                  print(i);

              Output:

              <class 'frozenset'>
              1
              2
              3
              4
              5
              6
              7
              8
              9

              Now we try to modify the frozenset. i.e We try to add an element.

              fset=frozenset([1, 2, 3, 4, 5, 6, 7, 8, 9])
              print(type(fset))
              print("\nNow we are trying to add the content in frozen set...")
              fset.add(10) # gives an error

              Output:

              <class 'frozenset'>
              Now we are trying to add the content in frozen set...
              AttributeError: 'frozenset' object has no attribute 'add'

              FrozenSet for the dictionary:
              If we take a dictionary as the element of a frozen set, it will take only the key element from the dictionary.
              Understand it by following example:

              Dictionary={"Name":"Abraham", "Country":"Jakarta", "EmpId":101}
              print(type(Dictionary))
              print(Dictionary)
              fset=frozenset(Dictionary)
              print(type(fset))
              print("\nFrozenset will take only key element from dictionary...")
              for i in fset:
                  print(i)

              Output:

              <class 'dict'>
              {'Name':'Abraham', 'Country':'Jakarta','EmpId':101}
              <class 'frozenset'>
              Frozenset will take only key element from dictionary...
              EmpId
              Name
              Country

              Some examples of Python Set:
              Example1: Write a program to remove the given number from the set.

              my_set={2, 4, 6, 8, 10, 12, 13, 14, 16, 18, 20}
              n=int(input("Enter the number you want to remove - "))
              my_set.discard(n)
              print("After removing, my numbers are:", my_set)

              Output:

              Enter the number you want to remove - 13
              After removing, my numbers are: 
              {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}

              Note: If the above program will not run in your compiler as whole then run it in two parts
              in first part run just above two lines, after that last two lines.

              Example2: Write a program to add multiple elements to the set

              my_set={"even","numbers", 2, 4, 6}
              my_set.update(["odd", "numbers", 1, 3, 5,7])
              print("separate even and odd numbers from the set", my_set)

              Output:

              separate even and odd numbers from the set{1, 2, 3, 4, 5, 6, 7, 'even', 'odd', 'numbers'}

              Example3: Write a program to find the union between two sets

              even_num={2, 4, 6, 8, 10}
              odd_num={1, 3, 5, 7, 9}
              natural_num=even_num.union(odd_num)
              print(natural_num)

              Output:

              {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

              Example4: Write  program to find intersection between two sets

              prime_num={1, 2, 3, 5, 7}
              odd_num={1, 3, 5, 7, 9}
              common_num=prime_num.intersection(odd_num)
              print(common_num)

              Output:

              {1, 3, 5, 7}

              Example5: Write a program to find issubset, issuperset superset

              month1={"January", "February", "March", "April"}
              month2={"January", "February"}
              month3={"January", "February", "May"}
              issuperset=month1>=month2
              print(issuperset)
              issubset=month1<=month2
              print(issubset)
              issuperset=month3>=month2
              print(issuperset)
              issubset=month3<=month2
              print(issubset)

              Output:

              True
              False
              True
              False

              Python built-in set methods:

              SN

              Method

              Description

              1

              add item()

              It adds an item to the set. It has no effect if the item is already present in the set.

              2

              clear()

              It deletes all the items from the set.

              3

              copy()

              It returns a copy of the set.

              4

              difference_update(….)

              It modifies this set by removing all the items that are also present in the specified sets.

              5

              discard(item)

              It removes the specified item from the set.

              6

              intersection()

              It returns a new set that contains only the common elements of both or more than two sets.

              7

              intersection_update(….)

              It removes the items from the original set that are not present in both or more than two sets.

              8

              isdisjoint(….)

              Return True if two sets have a null intersection.

              9

              issubset(….)

              Report whether another set contains this set.

              10

              issuperset(….)

              Report whether this set contains another set.

              11

              pop()

              Remove and return an arbitrary set element that is the last element of the set. Raises KeyError if the set is empty.

              12

              remove(item)

              Remove an element from a set. It must be a member. If the element is not the member of the set, it raises KeyError.

              13

              symmetric_difference(….)

              Remove an element from a set. It must be a member. If the element is not the member of the set, it raises KeyError.

              14

              symmetric_difference_update(….)

              Update a set with symmetric difference of itself and another.

              15

              union(….)

              Return the union of sets as a new set.

              16

              Update()

              Update a set with the union of itself and others.



              Python: Functions