Category: Python

  • Python Lambda Functions

    This tutorial will study anonymous, commonly called lambda functions in Python. A lambda function can take n number of arguments at a time. But it returns only one argument at a time. We will understand what they are, how to execute them, and their syntax.

    What are Lambda Functions in Python?

    Lambda Functions in Python are anonymous functions, implying they don’t have a name. The def keyword is needed to create a typical function in Python, as we already know. We can also use the lambda keyword in Python to define an unnamed function.

    Syntax

    The syntax of the Lambda Function is given below –

    1. lambda arguments: expression       

    This function accepts any count of inputs but only evaluates and returns one expression. That means it takes many inputs but returns only one output.

    Lambda functions can be used whenever function arguments are necessary. In addition to other forms of formulations in functions, it has a variety of applications in certain coding domains. It’s important to remember that according to syntax, lambda functions are limited to a single statement.

    Example

    Here we share some examples of lambda functions in Python for learning purposes. Program Code 1:

    Now we gave an example of a lambda function that adds 4 to the input number is shown below.

    # Code to demonstrate how we can use a lambda function for adding 4 numbers  
    
    add = lambda num: num + 4    
    
    print( add(6) )

    Output:

    Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -10

    Here we explain the above code. The lambda function is “lambda num: num+4” in the given programme. The parameter is num, and the computed and returned equation is num * 4.

    There is no label for this function. It generates a function object associated with the “add” identifier. We can now refer to it as a standard function. The lambda statement, “lambda num: num+4”, is written using the add function, and the code is given below: Program Code 2:

    Now we gave an example of a lambda function that adds 4 to the input number using the add function. The code is shown below –

    def add( num ):  
    
       return num + 4  
    
    print( add(6) )

    Output:

    Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -10

    Program Code 3:

    Now we gave an example of a lambda function that multiply 2 numbers and return one result. The code is shown below –

    a = lambda x, y : (x * y)  
    
    print(a(4, 5))

    Output:

    Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -20

    Program Code 4:

    Now we gave another example of a lambda function that adds 2 numbers and return one result. The code is shown below –

    a = lambda x, y, z : (x + y + z)  
    
    print(a(4, 5, 5))

    Output:

    Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -14

    What’s the Distinction Between Lambda and Def Functions?

    Let’s glance at this instance to see how a conventional def defined function differs from a function defined using the lambda keyword. This program calculates the reciprocal of a given number:

    # Python code to show the reciprocal of the given number to highlight the difference between def() and lambda().  
    
    def reciprocal( num ):  
    
        return 1 / num  
    
       
    
    lambda_reciprocal = lambda num: 1 / num  
    
       
    
    # using the function defined by def keyword  
    
    print( "Def keyword: ", reciprocal(6) )  
    
       
    
    # using the function defined by lambda keyword  
    
    print( "Lambda keyword: ", lambda_reciprocal(6) )

    Output:

    Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -Def keyword: 0.16666666666666666 Lambda keyword: 0.16666666666666666

    Explanation:

    The reciprocal() and lambda_reciprocal() functions act similarly and as expected in the preceding scenario. Let’s take a closer look at the sample above:

    Both of these yield the reciprocal of a given number without employing Lambda. However, we wanted to declare a function with the name reciprocal and send a number to it while executing def. We were also required to use the return keyword to provide the output from wherever the function was invoked after being executed.

    Using Lambda: Instead of a “return” statement, Lambda definitions always include a statement given at output. The beauty of lambda functions is their convenience. We need not allocate a lambda expression to a variable because we can put it at any place a function is requested.

    Using Lambda Function with filter()

    The filter() method accepts two arguments in Python: a function and an iterable such as a list.

    The function is called for every item of the list, and a new iterable or list is returned that holds just those elements that returned True when supplied to the function.

    Here’s a simple illustration of using the filter() method to return only odd numbers from a list.

    Program Code:

    Here we give an example of lambda function with filter() in Python. The code is given below –

    # This code used to filter the odd numbers from the given list  
    
    list_ = [35, 12, 69, 55, 75, 14, 73]      
    
    odd_list = list(filter( lambda num: (num % 2 != 0) , list_ ))      
    
    print('The list of odd number is:',odd_list)

    Output:

    Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -The list of odd number is: [35, 69, 55, 75, 73]

    Using Lambda Function with map()

    A method and a list are passed to Python’s map() function.

    The function is executed for all of the elements within the list, and a new list is produced with elements generated by the given function for every item.

    The map() method is used to square all the entries in a list in this example.

    Program Code:

    Here we give an example of lambda function with map() in Python. Then code is given below –

    #Code to calculate the square of each number of a list using the map() function      
    
    numbers_list = [2, 4, 5, 1, 3, 7, 8, 9, 10]      
    
    squared_list = list(map( lambda num: num ** 2 , numbers_list ))      
    
    print( 'Square of each number in the given list:' ,squared_list )

    Output:

    Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -Square of each number in the given list: [4, 16, 25, 1, 9, 49, 64, 81, 100]

    Using Lambda Function with List Comprehension

    In this instance, we will apply the lambda function combined with list comprehension and the lambda keyword with a for loop. Using the Lambda Function with List Comprehension, we can print the square value from 0 to 10. For printing the square value from 0 to 10, we create a loop range from 0 to 11.

    Program Code:

    Here we give an example of lambda function with List Comprehension in Python. Then code is given below –

    #Code to calculate square of each number of lists using list comprehension    
    
    squares = [lambda num = num: num ** 2 for num in range(0, 11)]       
    
    for square in squares:    
    
           print('The square value of all numbers from 0 to 10:',square(), end = " ")

    Output:

    Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -The square value of all numbers from 0 to 10: 0 1 4 9 16 25 36 49 64 81 100

    Using Lambda Function with if-else

    We will use the lambda function with the if-else block. In the program code below, we check which number is greater than the given two numbers using the if-else block.

    Program Code:

    Here we give an example of a lambda function with an if-else block in Python. The code is given below –

    # Code to use lambda function with if-else    
    
    Minimum = lambda x, y : x if (x < y) else y       
    
    print('The greater number is:', Minimum( 35, 74 ))

    Output:

    Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -The greater number is: 35

    Using Lambda with Multiple Statements

    Multiple expressions are not allowed in lambda functions, but we can construct 2 lambda functions or more and afterward call the second lambda expression as an argument to the first. We are sorting every sub-list from the given list in the below program. Let us use lambda to discover the third largest number from every sub-list.

    Program Code:

    Here we give an example of lambda function with Multiple Statements in Python. The code is given below –

    # Code to print the third largest number of the given list using the lambda function      
    
      
    
    my_List = [ [3, 5, 8, 6], [23, 54, 12, 87], [1, 2, 4, 12, 5] ]      
    
    # sorting every sublist of the above list    
    
    sort_List = lambda num : ( sorted(n) for n in num )      
    
    # Getting the third largest number of the sublist    
    
    third_Largest = lambda num, func : [ l[ len(l) - 2] for l in func(num)]    
    
    result = third_Largest( my_List, sort_List)      
    
    print('The third largest number from every sub list is:', result )

    Output:

    Now we compile the above code, in python and after successful compilation, we run it. Then the output is given below -The third largest number from every sub list is: [6, 54, 5]

    Conclusion:

    So, in this, we discuss the Lambda function in Python. A lambda function can take n number of arguments at a time. But it returns only one argument at a time. Here we discuss some lambda functions with the program code in Python, and we also share some examples of them. Here we discuss the Lambda function with the list, map, filter, multiple statements, if-else, and some basic programs of lambda function in Python.

  • Python Functions

    What are Python Functions?

    A collection of related assertions that carry out a mathematical, analytical, or evaluative operation is known as a function. An assortment of proclamations called Python Capabilities returns the specific errand. Python functions are necessary for intermediate-level programming and are easy to define. Function names meet the same standards 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 function and reuse the code it contains with different variables.

    Client-characterized and worked-in capabilities are the two primary classes of capabilities in Python. It aids in maintaining the program’s uniqueness, conciseness, and structure.

    Advantages of Python Functions

    Pause We can stop a program from repeatedly using the same code block by including functions.

    • Once defined, Python functions can be called multiple times and from any location in a program.
    • Our Python program can be broken up into numerous, easy-to-follow functions if it is significant.
    • The ability to return as many outputs as we want using a variety of arguments is one of Python’s most significant achievements.
    • However, Python programs have always incurred overhead when calling functions.

    However, calling functions has always been overhead in a Python program.

    Syntax

    #  An example Python Function  
    
    def function_name( parameters ):  
    
        # code block

    The accompanying components make up to characterize a capability, as seen previously.

    • 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.

    # Example Python Code for User-Defined function  
    
    def square( num ):    
    
        """  
    
        This function computes the square of the number.  
    
        """    
    
        return num**2     
    
    object_ = square(6)    
    
    print( "The square of the given number is: ", object_ )

    Output:The square of the given number is: 36

    Calling a Function

    Calling a Function To define a function, use the def keyword to give it a name, specify the arguments it must receive, and organize the code block.

    When the fundamental framework for a function is finished, we can call it from anywhere in the program. An illustration of how to use the a_function function can be found below.

    # Example Python Code for calling a function  
    
    # Defining a function    
    
    def a_function( string ):    
    
        "This prints the value of length of string"    
    
        return len(string)    
    
        
    
    # Calling the function we defined    
    
    print( "Length of the string Functions is: ", a_function( "Functions" ) )    
    
    print( "Length of the string Python is: ", a_function( "Python" ) )

    Output:Length of the string Functions is: 9 Length of the string Python is: 6

    Pass by Reference 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. For instance,

    Code

    # 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 l in item_list:    
    
            squares.append( l**2 )    
    
        return squares    
    
        
    
    # calling the defined function    
    
    my_list = [17, 52, 8];    
    
    my_result = square( my_list )    
    
    print( "Squares of the list are: ", my_result )

    Output:Squares of the list are: [289, 2704, 64]

    Function Arguments

    The following are the types of arguments that we can use to call a function:

    Default arguments
    
    Keyword arguments
    
    Required arguments
    
    Variable-length arguments

    1) Default Arguments

    A default contention is a boundary that takes as information a default esteem, assuming that no worth is provided for the contention when the capability is called. The following example demonstrates default arguments.

    Code

    # Python code to demonstrate the use of default arguments    
    
    # defining a function    
    
    def function( n1, n2 = 20 ):    
    
        print("number 1 is: ", n1)    
    
        print("number 2 is: ", n2)    
    
         
    
         
    
    # Calling the function and passing only one argument    
    
    print( "Passing only one argument" )    
    
    function(30)    
    
        
    
    # Now giving two arguments to the function    
    
    print( "Passing two arguments" )    
    
    function(50,30)

    Output:Passing only one argument number 1 is: 30 number 2 is: 20 Passing two arguments number 1 is: 50 number 2 is: 30

    2) Keyword Arguments

    Keyword arguments are linked to the arguments of a called function. While summoning a capability with watchword contentions, the client might tell whose boundary esteem it is by looking at the boundary name.

    We can eliminate or orchestrate specific contentions in an alternate request since the Python translator will interface the furnished watchwords to connect the qualities with its boundaries. One more method for utilizing watchwords to summon the capability() strategy is as per the following:

    Code

    # Python code to demonstrate the use of keyword arguments    
    
      # Defining a function    
    
    def function( n1, n2 ):    
    
        print("number 1 is: ", n1)    
    
        print("number 2 is: ", n2)    
    
        
    
    # Calling function and passing arguments without using keyword    
    
    print( "Without using keyword" )    
    
    function( 50, 30)       
    
            
    
    # Calling function and passing arguments using keyword    
    
    print( "With using keyword" )    
    
    function( n2 = 50, n1 = 30)

    Output:Without using keyword number 1 is: 50 number 2 is: 30 With using keyword number 1 is: 30 number 2 is: 50

    3) Required Arguments

    Required arguments are those supplied to a function during its call in a predetermined positional sequence. The number of arguments required in the method call must be the same as those provided in the function’s definition.

    We should send two contentions to the capability() all put together; it will return a language structure blunder, as seen beneath.

    Code

    # Python code to demonstrate the use of default arguments      
    
    # Defining a function    
    
    def function( n1, n2 ):    
    
        print("number 1 is: ", n1)    
    
        print("number 2 is: ", n2)    
    
        
    
    # Calling function and passing two arguments out of order, we need num1 to be 20 and num2 to be 30    
    
    print( "Passing out of order arguments" )    
    
    function( 30, 20 )       
    
        
    
    # Calling function and passing only one argument    
    
    print( "Passing only one argument" )    
    
    try:    
    
        function( 30 )    
    
    except:    
    
        print( "Function needs two positional arguments" )

    Output:Passing out of order arguments number 1 is: 30 number 2 is: 20 Passing only one argument Function needs two positional arguments

    4) Variable-Length Arguments

    We can involve unique characters in Python capabilities to pass many contentions. However, we need a capability. This can be accomplished with one of two types of characters:

    “args” and “kwargs” refer to arguments not based on keywords.

    To help you understand arguments of variable length, here’s an example.

    Code

    # Python code to demonstrate the use of variable-length arguments       
    
    # Defining a function    
    
    def function( *args_list ):    
    
        ans = []    
    
        for l in args_list:    
    
            ans.append( l.upper() )    
    
        return ans    
    
    # Passing args arguments    
    
    object = function('Python', 'Functions', 'tutorial')    
    
    print( object )    
    
        
    
    # defining a function    
    
    def function( **kargs_list ):    
    
        ans = []    
    
        for key, value in kargs_list.items():    
    
            ans.append([key, value])    
    
        return ans    
    
    # Paasing kwargs arguments    
    
    object = function(First = "Python", Second = "Functions", Third = "Tutorial")    
    
    print(object)

    Output:[‘PYTHON’, ‘FUNCTIONS’, ‘TUTORIAL’] [[‘First’, ‘Python’], [‘Second’, ‘Functions’], [‘Third’, ‘Tutorial’]]

    return Statement

    When a defined function is called, a return statement is written to exit the function and return the calculated value.

    Syntax:

    return < expression to be returned as output >    

    The return statement can be an argument, a statement, or a value, and it is provided as output when a particular job or function is finished. A declared function will return an empty string if no return statement is written.

    A return statement in Python functions is depicted in the following example.

    Code

    # Python code to demonstrate the use of return statements      
    
    # Defining a function with return statement    
    
    def square( num ):    
    
        return num**2    
    
         
    
    # Calling function and passing arguments.    
    
    print( "With return statement" )    
    
    print( square( 52 ) )    
    
        
    
    # Defining a function without return statement     
    
    def square( num ):    
    
         num**2     
    
        
    
    # Calling function and passing arguments.    
    
    print( "Without return statement" )    
    
    print( square( 52 ) )

    Output:With return statement 2704 Without return statement None

    The Anonymous Functions

    Since we do not use the def keyword to declare these kinds of Python functions, they are unknown. The lambda keyword can define anonymous, short, single-output functions.

    Arguments can be accepted in any number by lambda expressions; However, the function only produces a single value from them. They cannot contain multiple instructions or expressions. Since lambda needs articulation, a mysterious capability can’t be straightforwardly called to print.

    Lambda functions can only refer to variables in their argument list and the global domain name because they contain their distinct local domain.

    In contrast to inline expressions in C and C++, which pass function stack allocations at execution for efficiency reasons, lambda expressions appear to be one-line representations of functions.

    Syntax

    Lambda functions have exactly one line in their syntax:

    1. lambda [argument1 [,argument2… .argumentn]] : expression    

    Below is an illustration of how to use the lambda function:

    Code

    # Python code to demonstrate ananymous functions  
    
    # Defining a function    
    
    lambda_ = lambda argument1, argument2: argument1 + argument2;    
    
        
    
    # Calling the function and passing values    
    
    print( "Value of the function is : ", lambda_( 20, 30 ) )    
    
    print( "Value of the function is : ", lambda_( 40, 50 ) )

    Output:Value of the function is : 50 Value of the function is : 90

    Scope and Lifetime of Variables

    A variable’s scope refers to the program’s domain wherever it is declared. A capability’s contentions and factors are not external to the characterized capability. They only have a local domain as a result.

    The length of time a variable remains in RAM is its lifespan. The lifespan of a function is the same as the lifespan of its internal variables. When we exit the function, they are taken away from us. As a result, the value of a variable in a function does not persist from previous executions.

    An easy illustration of a function’s scope for a variable can be found here.

    Code

    
    
    1. # Python code to demonstrate scope and lifetime of variables  
    2. #defining a function to print a number.    
    3. def number( ):    
    4.     num = 50    
    5.     print( "Value of num inside the function: ", num)    
    6.     
    7. num = 10    
    8. number()    
    9. print( "Value of num outside the function:", num)    

    Output:Value of num inside the function: 50 Value of num outside the function: 10

    Here, we can see that the initial value of num is 10. Even though the function number() changed the value of num to 50, the value of num outside of the function remained unchanged.

    This is because the capability’s interior variable num is not quite the same as the outer variable (nearby to the capability). Despite having a similar variable name, they are separate factors with discrete extensions.

    Factors past the capability are available inside the capability. The impact of these variables is global. We can retrieve their values within the function, but we cannot alter or change them. The value of a variable can be changed outside of the function if it is declared global with the keyword global.

    Python Capability inside Another Capability

    Capabilities are viewed as top-of-the-line objects in Python. First-class objects are treated the same everywhere they are used in a programming language. They can be stored in built-in data structures, used as arguments, and in conditional expressions. If a programming language treats functions like first-class objects, it is considered to implement first-class functions. Python lends its support to the concept of First-Class functions.

    A function defined within another is called an “inner” or “nested” function. The parameters of the outer scope are accessible to inner functions. Internal capabilities are developed to cover them from the progressions outside the capability. Numerous designers see this interaction as an embodiment.

    Code

    # Python code to show how to access variables of a nested functions    
    
    # defining a nested function    
    
    def word():    
    
        string = 'Python functions tutorial'    
    
        x = 5     
    
        def number():    
    
            print( string )   
    
            print( x )  
    
                 
    
        number()    
    
    word()

    Output:Python functions tutorial 5

  • Python Dictionary

    Dictionaries are a useful data structure for storing data in Python because they are capable of imitating real-world data arrangements where a certain value exists for a given key.

    The data is stored as key-value pairs using a Python dictionary.

    • This data structure is mutable
    • The components of dictionary were made using keys and values.
    • Keys must only have one component.
    • Values can be of any type, including integer, list, and tuple.

    A dictionary is, in other words, a group of key-value pairs, where the values can be any Python object. The keys, in contrast, are immutable Python objects, such as strings, tuples, or numbers. Dictionary entries are ordered as of Python version 3.7. In Python 3.6 and before, dictionaries are generally unordered.

    Creating the Dictionary

    Curly brackets are the simplest way to generate a Python dictionary, although there are other approaches as well. With many key-value pairs surrounded in curly brackets and a colon separating each key from its value, the dictionary can be built. (:). The following provides the syntax for defining the dictionary.

    Syntax:

    Dict = {"Name": "Gayle", "Age": 25}
    

    In the above dictionary Dict, The keys Name and Age are the strings which comes under the category of an immutable object.

    Let’s see an example to create a dictionary and print its content.

    Code

    Employee = {"Name": "Johnny", "Age": 32, "salary":26000,"Company":"^TCS"}        
    
    print(type(Employee))        
    
    print("printing Employee data .... ")        
    
    print(Employee)

    Output<class ‘dict’> printing Employee data …. {‘Name’: ‘Johnny’, ‘Age’: 32, ‘salary’: 26000, ‘Company’: TCS}

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

    The empty curly braces {} 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({1: 'Hcl', 2: 'WIPRO', 3:'Facebook'})       
    
    print("\nCreate Dictionary by using  dict(): ")       
    
    print(Dict)       
    
          
    
    # Creating a Dictionary       
    
    # with each item as a Pair       
    
    Dict = dict([(4, 'Rinku'), (2, Singh)])       
    
    print("\nDictionary with each item as a pair: ")       
    
    print(Dict)

    OutputEmpty Dictionary: {} Create Dictionary by using dict(): {1: ‘Hcl’, 2: ‘WIPRO’, 3: ‘Facebook’} Dictionary with each item as a pair: {4: ‘Rinku’, 2: ‘Singh’}

    Accessing the dictionary values

    To access data contained in lists and tuples, indexing has been studied. The keys of the dictionary can be used to obtain the values because they are unique from one another. The following method can be used to access dictionary values.

    Code

    Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}      
    
    print(type(Employee))      
    
    print("printing Employee data .... ")      
    
    print("Name : %s" %Employee["Name"])      
    
    print("Age : %d" %Employee["Age"])      
    
    print("Salary : %d" %Employee["salary"])      
    
    print("Company : %s" %Employee["Company"])

    Outputee[“Company”]) Output <class ‘dict’> printing Employee data …. Name : Dev Age : 20 Salary : 45000 Company : WIPRO

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

    Adding Dictionary Values

    The dictionary is a mutable data type, and utilising the right keys allows you to change its values. Dict[key] = value and the value can both be modified. An existing value can also be updated using the update() method.

    Note: The value is updated if the key-value pair is already present in the dictionary. Otherwise, the dictionary’s newly added keys.

    Let’s see an example to update the dictionary values.

    Example – 1:

    Code

    # Creating an empty Dictionary       
    
    Dict = {}       
    
    print("Empty Dictionary: ")       
    
    print(Dict)       
    
            
    
    # Adding elements to dictionary one at a time       
    
    Dict[0] = 'Peter'      
    
    Dict[2] = 'Joseph'      
    
    Dict[3] = 'Ricky'      
    
    print("\nDictionary after adding 3 elements: ")       
    
    print(Dict)       
    
            
    
    # Adding set of values        
    
    # with a single Key       
    
    # The Emp_ages doesn't exist to dictionary      
    
    Dict['Emp_ages'] = 20, 33, 24      
    
    print("\nDictionary after adding 3 elements: ")       
    
    print(Dict)       
    
      
    
    # Updating existing Key's Value       
    
    Dict[3] = 'JavaTpoint'      
    
    print("\nUpdated key value: ")       
    
    print(Dict)

    OutputEmpty Dictionary: {} Dictionary after adding 3 elements: {0: ‘Peter’, 2: ‘Joseph’, 3: ‘Ricky’} Dictionary after adding 3 elements: {0: ‘Peter’, 2: ‘Joseph’, 3: ‘Ricky’, ‘Emp_ages’: (20, 33, 24)} Updated key value: {0: ‘Peter’, 2: ‘Joseph’, 3: ‘JavaTpoint’, ‘Emp_ages’: (20, 33, 24)}

    Example – 2:

    Code

    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: Sunny Age: 38 Salary: 39000 Company:Hcl printing the new data {‘Name’: ‘Sunny’, ‘Age’: 38, ‘salary’: 39000, ‘Company’: ‘Hcl’}

    Deleting Elements using del Keyword

    The items of the dictionary can be deleted by using the del keyword as given below.

    Code

    Employee = {"Name": "David", "Age": 30, "salary":55000,"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 information ")        
    
    print(Employee)        
    
    print("Deleting the dictionary: Employee");        
    
    del Employee        
    
    print("Lets try to print it again ");        
    
    print(Employee)

    Output<class ‘dict’> printing Employee data …. {‘Name’: ‘David’, ‘Age’: 30, ‘salary’: 55000, ‘Company’: ‘WIPRO’} Deleting some of the employee data printing the modified information {‘Age’: 30, ‘salary’: 55000} Deleting the dictionary: Employee Lets try to print it again NameError: name ‘Employee’ is not defined.

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

    Deleting Elements using pop() Method

    A dictionary is a group of key-value pairs in Python. You can retrieve, insert, and remove items using this unordered, mutable data type by using their keys. The pop() method is one of the ways to get rid of elements from a dictionary. In this post, we’ll talk about how to remove items from a Python dictionary using the pop() method.

    The value connected to a specific key in a dictionary is removed using the pop() method, which then returns the value. The key of the element to be removed is the only argument needed. The pop() method can be used in the following ways:

    Code

    # Creating a Dictionary       
    
    Dict1 = {1: 'JavaTpoint', 2: 'Educational', 3: 'Website'}       
    
    # Deleting a key        
    
    # using pop() method       
    
    pop_key = Dict1.pop(2)       
    
    print(Dict1)

    Output{1: ‘JavaTpoint’, 3: ‘Website’}

    Additionally, Python offers built-in functions popitem() and clear() for removing dictionary items. In contrast to the clear() method, which removes all of the elements from the entire dictionary, popitem() removes any element from a dictionary.

    Iterating Dictionary

    A dictionary can be iterated using for loop as given below.

    Example 1

    Code

    # for loop to print all the keys of a dictionary    
    
    Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}        
    
    for x in Employee:        
    
        print(x)

    OutputName Age salary Company

    Example 2

    Code

    #for loop to print all the values of the dictionary    
    
    Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"} for x in Employee:        
    
     print(Employee[x])

    OutputJohn 29 25000 WIPRO

    Example – 3

    Code

    #for loop to print the values of the dictionary by using values() method.    
    
    Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}        
    
    for x in Employee.values():        
    
        print(x)

    OutputJohn 29 25000 WIPRO

    Example 4

    Code

    #for loop to print the items of the dictionary by using items() method    
    
    Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}       
    
    for x in Employee.items():        
    
        print(x)

    Output(‘Name’, ‘John’) (‘Age’, 29) (‘salary’, 25000) (‘Company’, ‘WIPRO’)

    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

    Employee={"Name":"John","Age":29,"Salary":25000,"Company":"WIPRO","Name":    
    
    "John"}        
    
    for x,y in Employee.items():        
    
            print(x,y)

    OutputName John Age 29 Salary 25000 Company WIPRO

    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

    Employee = {"Name": "John", "Age": 29, "salary":26000,"Company":"WIPRO",[100,201,301]:"Department ID"}        
    
    for x,y in Employee.items():        
    
        print(x,y)

    OutputTraceback (most recent call last): File “dictionary.py”, line 1, in Employee = {“Name”: “John”, “Age”: 29, “salary”:26000,”Company”:”WIPRO”,[100,201,301]:”Department ID”} TypeError: unhashable type: ‘list’

    Built-in Dictionary Functions

    A function is a method that can be used on a construct to yield a value. Additionally, the construct is unaltered. A few of the Python methods can be combined with a Python dictionary.

    The built-in Python dictionary 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: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}  
    
    len(dict)

    Output4

    • 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: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}  
    
    any({'':'','':'','3':''})

    OutputTrue

    • all()

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

    Code

    dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}  
    
    all({1:'',2:'','':''})

    OutputFalse

    • sorted()

    Like it does with lists and tuples, 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 = {7: "Ayan", 5: "Bunny", 8: "Ram", 1: "Bheem"}  
    
    sorted(dict)

    Output[ 1, 5, 7, 8]

    Built-in Dictionary methods

    The built-in python dictionary methods along with the description and Code are given below.

    • clear()

    It is mainly used to delete all the items of the dictionary.

    Code

    # dictionary methods    
    
    dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}    
    
    # clear() method    
    
    dict.clear()    
    
    print(dict)

    Output{ }

    • copy()

    It returns a shallow copy of the dictionary which is created.

    Code

    # dictionary methods    
    
    dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}    
    
    # copy() method    
    
    dict_demo = dict.copy()    
    
    print(dict_demo)

    Output{1: ‘Hcl’, 2: ‘WIPRO’, 3: ‘Facebook’, 4: ‘Amazon’, 5: ‘Flipkart’}

    • pop()

    It mainly eliminates the element using the defined key.

    Code

    # dictionary methods    
    
    dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}    
    
    # pop() method    
    
    dict_demo = dict.copy()    
    
    x = dict_demo.pop(1)    
    
    print(x)

    Output{2: ‘WIPRO’, 3: ‘Facebook’, 4: ‘Amazon’, 5: ‘Flipkart’}

    popitem()

    removes the most recent key-value pair entered

    Code

    # dictionary methods    
    
    dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}    
    
    # popitem() method    
    
    dict_demo.popitem()    
    
    print(dict_demo)

    Output{1: ‘Hcl’, 2: ‘WIPRO’, 3: ‘Facebook’}

    • keys()

    It returns all the keys of the dictionary.

    Code

    # dictionary methods    
    
    dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}    
    
    # keys() method    
    
    print(dict_demo.keys())

    Outputdict_keys([1, 2, 3, 4, 5])

    • items()

    It returns all the key-value pairs as a tuple.

    Code

    # dictionary methods    
    
    dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}    
    
    # items() method    
    
    print(dict_demo.items())

    Outputdict_items([(1, ‘Hcl’), (2, ‘WIPRO’), (3, ‘Facebook’), (4, ‘Amazon’), (5, ‘Flipkart’)])

    • get()

    It is used to get the value specified for the passed key.

    Code

    # dictionary methods    
    
    dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}    
    
    # get() method    
    
    print(dict_demo.get(3))

    OutputFacebook

    • update()

    It mainly updates all the dictionary by adding the key-value pair of dict2 to this dictionary.

    Code

    # dictionary methods    
    
    dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}    
    
    # update() method    
    
    dict_demo.update({3: "TCS"})    
    
    print(dict_demo)

    Output{1: ‘Hcl’, 2: ‘WIPRO’, 3: ‘TCS’}

    • values()

    It returns all the values of the dictionary with respect to given input.

    
    
    1. # dictionary methods    
    2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}    
    3. # values() method    
    4. print(dict_demo.values())

    Outputdict_values([‘Hcl’, ‘WIPRO’, ‘TCS’])

  • Python Set

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

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

    Creating a set

    The set can be created by enclosing the comma-separated immutable items with the 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 = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}    
    
    print(Days)    
    
    print(type(Days))    
    
    print("looping through the set elements ... ")    
    
    for i in Days:    
    
        print(i)

    Output:{‘Friday’, ‘Tuesday’, ‘Monday’, ‘Saturday’, ‘Thursday’, ‘Sunday’, ‘Wednesday’} <class ‘set’> looping through the set elements … Friday Tuesday Monday Saturday Thursday Sunday Wednesday

    Example 2: Using set() method

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

    Output:{‘Friday’, ‘Wednesday’, ‘Thursday’, ‘Saturday’, ‘Monday’, ‘Tuesday’, ‘Sunday’} <class ‘set’> looping through the set elements … Friday Wednesday Thursday Saturday Monday Tuesday Sunday

    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, "JavaTpoint", 20.5, 14}  
    
    print(type(set1))  
    
    #Creating a set which have mutable element  
    
    set2 = {1,2,3,["Javatpoint",4]}  
    
    print(type(set2))

    Output:<class ‘set’> Traceback (most recent call last) <ipython-input-5-9605bb6fbc68> in <module> 4 5 #Creating a set which holds mutable elements —-> 6 set2 = {1,2,3,[“Javatpoint”,4]} 7 print(type(set2)) TypeError: unhashable type: ‘list’

    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 contain only immutable elements.

    Creating an empty set is a bit 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 happened if we provide the duplicate element to the set.

    set5 = {1,2,4,4,5,8,9,9,10}  
    
    print("Return set with unique elements:",set5)

    Output:Return set with unique elements: {1, 2, 4, 5, 8, 9, 10}

    In the above code, we can see that set5 consisted of multiple duplicate elements when we printed it remove the duplicity 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

    Months = set(["January","February", "March", "April", "May", "June"])    
    
    print("\nprinting the original set ... ")    
    
    print(months)    
    
    print("\nAdding other months to the set...");    
    
    Months.add("July");    
    
    Months.add ("August");    
    
    print("\nPrinting the modified set...");    
    
    print(Months)    
    
    print("\nlooping through the set elements ... ")    
    
    for i in Months:    
    
        print(i)

    Output:printing the original set … {‘February’, ‘May’, ‘April’, ‘March’, ‘June’, ‘January’} Adding other months to the set… Printing the modified set… {‘February’, ‘July’, ‘May’, ‘April’, ‘March’, ‘August’, ‘June’, ‘January’} looping through the set elements … February July May April March August June January

    To add more than one item in the set, Python provides the update() method. It accepts iterable as an argument.

    Consider the following example.

    Example – 2 Using update() function

    Months = set(["January","February", "March", "April", "May", "June"])    
    
    print("\nprinting the original set ... ")    
    
    print(Months)    
    
    print("\nupdating the original set ... ")    
    
    Months.update(["July","August","September","October"]);    
    
    print("\nprinting the modified set ... ")     
    
    print(Months);

    Output:printing the original set … {‘January’, ‘February’, ‘April’, ‘May’, ‘June’, ‘March’} updating the original set … printing the modified set … {‘January’, ‘February’, ‘April’, ‘August’, ‘October’, ‘May’, ‘June’, ‘July’, ‘September’, ‘March’}

    Removing items from the set

    Python provides the discard() method and remove() method which can be used to remove the items from the set. The difference between these function, using discard() function if the item does not exist in the set then the set remain unchanged whereas remove() method will through an error.

    Consider the following example.

    Example-1 Using discard() method

    months = set(["January","February", "March", "April", "May", "June"])    
    
    print("\nprinting the original set ... ")    
    
    print(months)    
    
    print("\nRemoving some months from the set...");    
    
    months.discard("January");    
    
    months.discard("May");    
    
    print("\nPrinting the modified set...");    
    
    print(months)    
    
    print("\nlooping through the set elements ... ")    
    
    for i in months:    
    
        print(i)

    Output:printing the original set … {‘February’, ‘January’, ‘March’, ‘April’, ‘June’, ‘May’} Removing some months from the set… Printing the modified set… {‘February’, ‘March’, ‘April’, ‘June’} looping through the set elements … February March April June

    Python provides also the remove() method to remove the item from the set. Consider the following example to remove the items using remove() method.

    Example-2 Using remove() function

    months = set(["January","February", "March", "April", "May", "June"])    
    
    print("\nprinting the original set ... ")    
    
    print(months)    
    
    print("\nRemoving some months from the set...");    
    
    months.remove("January");    
    
    months.remove("May");    
    
    print("\nPrinting the modified set...");    
    
    print(months)

    Output:printing the original set … {‘February’, ‘June’, ‘April’, ‘May’, ‘January’, ‘March’} Removing some months from the set… Printing the modified set… {‘February’, ‘June’, ‘April’, ‘March’}

    We can also use the pop() method to remove the item. Generally, the pop() method will always remove the last item but the set is unordered, we can’t determine which element will be popped from set.

    Consider the following example to remove the item from the set using pop() method.

    Months = set(["January","February", "March", "April", "May", "June"])    
    
    print("\nprinting the original set ... ")    
    
    print(Months)    
    
    print("\nRemoving some months from the set...");    
    
    Months.pop();    
    
    Months.pop();    
    
    print("\nPrinting the modified set...");    
    
    print(Months)

    Output:printing the original set … {‘June’, ‘January’, ‘May’, ‘April’, ‘February’, ‘March’} Removing some months from the set… Printing the modified set… {‘May’, ‘April’, ‘February’, ‘March’}

    In the above code, the last element of the Month set is March but the pop() method removed the June and January because the set is unordered and the pop() method could not determine the last element of the set.

    Python provides the clear() method to remove all the items from the set.

    Consider the following example.

    Months = set(["January","February", "March", "April", "May", "June"])    
    
    print("\nprinting the original set ... ")    
    
    print(Months)    
    
    print("\nRemoving all the items from the set...");    
    
    Months.clear()    
    
    print("\nPrinting the modified set...")    
    
    print(Months)

    Output:printing the original set … {‘January’, ‘May’, ‘June’, ‘April’, ‘March’, ‘February’} Removing all the items from the set… Printing the modified set… set()

    Difference between discard() and remove()

    Despite the fact that discard() and remove() method both perform the same task, There is one main difference between discard() and remove().

    If the key to be deleted from the set using discard() doesn’t exist in the set, the Python will not give the error. The program maintains its control flow.

    On the other hand, if the item to be deleted from the set using remove() doesn’t exist in the set, the Python will raise an error.

    Consider the following example.

    Example-

    Months = set(["January","February", "March", "April", "May", "June"])    
    
    print("\nprinting the original set ... ")    
    
    print(Months)    
    
    print("\nRemoving items through discard() method...");    
    
    Months.discard("Feb"); #will not give an error although the key feb is not available in the set    
    
    print("\nprinting the modified set...")    
    
    print(Months)    
    
    print("\nRemoving items through remove() method...");    
    
    Months.remove("Jan") #will give an error as the key jan is not available in the set.     
    
    print("\nPrinting the modified set...")    
    
    print(Months)

    Output:printing the original set … {‘March’, ‘January’, ‘April’, ‘June’, ‘February’, ‘May’} Removing items through discard() method… printing the modified set… {‘March’, ‘January’, ‘April’, ‘June’, ‘February’, ‘May’} Removing items through remove() method… Traceback (most recent call last): File “set.py”, line 9, in Months.remove(“Jan”) KeyError: ‘Jan’

    Python Set Operations

    Set can be performed mathematical operation such as union, intersection, difference, and symmetric difference. Python provides the facility to carry out these operations with operators or methods. We describe these operations as follows.

    Union of two Sets

    To combine two or more sets into one set in Python, use the union() function. All of the distinctive characteristics from each combined set are present in the final set. As parameters, one or more sets may be passed to the union() function. The function returns a copy of the set supplied as the lone parameter if there is just one set. The method returns a new set containing all the different items from all the arguments if more than one set is supplied as an argument.

    Python Set

    Consider the following example to calculate the union of two sets.

    Example 1: using union | operator

    Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"}    
    
    Days2 = {"Friday","Saturday","Sunday"}    
    
    print(Days1|Days2) #printing the union of the sets

    Output:{‘Friday’, ‘Sunday’, ‘Saturday’, ‘Tuesday’, ‘Wednesday’, ‘Monday’, ‘Thursday’}

    Python also provides the union() method which can also be used to calculate the union of two sets. Consider the following example.

    Example 2: using union() method

    Days1 = {"Monday","Tuesday","Wednesday","Thursday"}    
    
    Days2 = {"Friday","Saturday","Sunday"}    
    
    print(Days1.union(Days2)) #printing the union of the sets

    Output:{‘Friday’, ‘Monday’, ‘Tuesday’, ‘Thursday’, ‘Wednesday’, ‘Sunday’, ‘Saturday’}

    Now, we can also make the union of more than two sets using the union() function, for example:

    Program:

    # Create three sets  
    
    set1 = {1, 2, 3}  
    
    set2 = {2, 3, 4}  
    
    set3 = {3, 4, 5}  
    
      
    
    # Find the common elements between the three sets  
    
    common_elements = set1.union(set2, set3)  
    
      
    
    # Print the common elements  
    
    print(common_elements)

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

    The intersection of two sets

    To discover what is common between two or more sets in Python, apply the intersection() function. Only the items in all sets being compared are included in the final set. One or more sets can also be used as the intersection() function parameters. The function returns a copy of the set supplied as the lone parameter if there is just one set. The method returns a new set that only contains the elements in all the compared sets if multiple sets are supplied as arguments.

    The intersection of two sets can be performed by the and & operator or the intersection() function. The intersection of the two sets is given as the set of the elements that common in both sets.

    Python Set

    Consider the following example.

    Example 1: Using & operator

    Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"}    
    
    Days2 = {"Monday","Tuesday","Sunday", "Friday"}    
    
    print(Days1&Days2) #prints the intersection of the two sets

    Output:{‘Monday’, ‘Tuesday’}

    Example 2: Using intersection() method

    set1 = {"Devansh","John", "David", "Martin"}    
    
    set2 = {"Steve", "Milan", "David", "Martin"}    
    
    print(set1.intersection(set2)) #prints the intersection of the two sets

    Output:{‘Martin’, ‘David’}

    Example 3:

    
    
    1. set1 = {1,2,3,4,5,6,7}  
    2. set2 = {1,2,20,32,5,9}  
    3. set3 = set1.intersection(set2)  
    4. print(set3)  

    Output:{1,2,5}

    Similarly, as the same as union function, we can perform the intersection of more than two sets at a time,

    For Example:

    Program

    # Create three sets  
    
    set1 = {1, 2, 3}  
    
    set2 = {2, 3, 4}  
    
    set3 = {3, 4, 5}  
    
      
    
    # Find the common elements between the three sets  
    
    common_elements = set1.intersection(set2, set3)  
    
      
    
    # Print the common elements  
    
    print(common_elements)

    Output:{3}

    The intersection_update() method

    The intersection_update() method removes the items from the original set that are not present in both the sets (all the sets if more than one are specified).

    The intersection_update() method is different from the intersection() method since it modifies the original set by removing the unwanted items, on the other hand, the intersection() method returns a new set.

    Consider the following example.

    a = {"Devansh", "bob", "castle"}    
    
    b = {"castle", "dude", "emyway"}    
    
    c = {"fuson", "gaurav", "castle"}    
    
        
    
    a.intersection_update(b, c)    
    
        
    
    print(a)

    Output:{‘castle’}

    Difference between the two sets

    The difference of two sets can be calculated by using the subtraction (-) operator or intersection() method. Suppose there are two sets A and B, and the difference is A-B that denotes the resulting set will be obtained that element of A, which is not present in the set B.

    Python Set

    Consider the following example.

    Example 1 : Using subtraction ( – ) operator

    Days1 = {"Monday",  "Tuesday", "Wednesday", "Thursday"}    
    
    Days2 = {"Monday", "Tuesday", "Sunday"}    
    
    print(Days1-Days2) #{"Wednesday", "Thursday" will be printed}

    Output:{‘Thursday’, ‘Wednesday’}

    Example 2 : Using difference() method

    Days1 = {"Monday",  "Tuesday", "Wednesday", "Thursday"}    
    
    Days2 = {"Monday", "Tuesday", "Sunday"}    
    
    print(Days1.difference(Days2)) # prints the difference of the two sets Days1 and Days2

    Output:{‘Thursday’, ‘Wednesday’}

    Symmetric Difference of two sets

    In Python, the symmetric Difference between set1 and set2 is the set of elements present in one set or the other but not in both sets. In other words, the set of elements is in set1 or set2 but not in their intersection.

    The Symmetric Difference of two sets can be computed using Python’s symmetric_difference() method. This method returns a new set containing all the elements in either but not in both. Consider the following example:

    Python Set

    Example – 1: Using ^ operator

    a = {1,2,3,4,5,6}  
    
    b = {1,2,9,8,10}  
    
    c = a^b  
    
    print(c)

    Output:{3, 4, 5, 6, 8, 9, 10}

    Example – 2: Using symmetric_difference() method

    a = {1,2,3,4,5,6}  
    
    b = {1,2,9,8,10}  
    
    c = a.symmetric_difference(b)  
    
    print(c)

    Output:{3, 4, 5, 6, 8, 9, 10}

    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 two sets have the same elements, regardless of their order.
    • !=: checks if two sets are not equal.
    • <: checks if the left set is a proper subset of the right set (i.e., all elements in the left set are also in the right set, but the right set has additional elements).
    • <=: checks if the left set is a 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 a proper superset of the right set (i.e., all elements in the right set are also in the left set, but the left set has additional elements).
    • >=: checks if the left set is a superset of the right set (i.e., all elements in the right set are also in the left).

    Consider the following example.

    Days1 = {"Monday",  "Tuesday", "Wednesday", "Thursday"}    
    
    Days2 = {"Monday", "Tuesday"}    
    
    Days3 = {"Monday", "Tuesday", "Friday"}    
    
        
    
    #Days1 is the superset of Days2 hence it will print true.     
    
    print (Days1>Days2)     
    
        
    
    #prints false since Days1 is not the subset of Days2     
    
    print (Days1<Days2)    
    
        
    
    #prints false since Days2 and Days3 are not equivalent     
    
    print (Days2 == Days3)

    Output:True False False

    FrozenSets

    In Python, a frozen set is an immutable version of the built-in set data type. It is similar to a set, but its contents cannot be changed once a frozen set is created.

    Frozen set objects are unordered collections of unique elements, just like sets. They can be used the same way as sets, except they cannot be modified. Because they are immutable, frozen set objects can be used as elements of other sets or dictionary keys, while standard sets cannot.

    One of the main advantages of using frozen set objects is that they are hashable, meaning they can be used as keys in dictionaries or as elements of other sets. Their contents cannot change, so their hash values remain constant. Standard sets are not hashable because they can be modified, so their hash values can change.

    Frozen set objects support many of the assets of the same operation, such as union, intersection, Difference, and symmetric Difference. They also support operations that do not modify the frozen set, such as len(), min(), max(), and in.

    Consider the following example to create the frozen set.

    
    
    1. Frozenset = frozenset([1,2,3,4,5])     
    2. print(type(Frozenset))    
    3. print("\nprinting the content of frozen set...")    
    4. for i in Frozenset:    
    5.     print(i);    
    6. Frozenset.add(6) #gives an error since we cannot change the content of Frozenset after creation    

    Output:<class ‘frozenset’> printing the content of frozen set… 1 2 3 4 5 Traceback (most recent call last): File “set.py”, line 6, in <module> Frozenset.add(6) #gives an error since we can change the content of Frozenset after creation AttributeError: ‘frozenset’ object has no attribute ‘add’

    Frozenset for the dictionary

    If we pass the dictionary as the sequence inside the frozenset() method, it will take only the keys from the dictionary and returns a frozenset that contains the key of the dictionary as its elements.

    Consider the following example.

    Dictionary = {"Name":"John", "Country":"USA", "ID":101}     
    
    print(type(Dictionary))    
    
    Frozenset = frozenset(Dictionary); #Frozenset will contain the keys of the dictionary    
    
    print(type(Frozenset))    
    
    for i in Frozenset:     
    
        print(i)

    Output:<class ‘dict’> <class ‘frozenset’> Name Country ID

    Set Programming Example

    Example – 1: Write a program to remove the given number from the set.

    my_set = {1,2,3,4,5,6,12,24}  
    
    n = int(input("Enter the number you want to remove"))  
    
    my_set.discard(n)  
    
    print("After Removing:",my_set)

    Output:Enter the number you want to remove:12 After Removing: {1, 2, 3, 4, 5, 6, 24}

    Example – 2: Write a program to add multiple elements to the set.

    set1 = set([1,2,4,"John","CS"])  
    
    set1.update(["Apple","Mango","Grapes"])  
    
    print(set1)

    Output:{1, 2, 4, ‘Apple’, ‘John’, ‘CS’, ‘Mango’, ‘Grapes’}

    Example – 3: Write a program to find the union between two set.

    set1 = set(["Peter","Joseph", 65,59,96])  
    
    set2  = set(["Peter",1,2,"Joseph"])  
    
    set3 = set1.union(set2)  
    
    print(set3)

    Output:{96, 65, 2, ‘Joseph’, 1, ‘Peter’, 59}

    Example- 4: Write a program to find the intersection between two sets.

    set1 = {23,44,56,67,90,45,"Javatpoint"}  
    
    set2 = {13,23,56,76,"Sachin"}  
    
    set3 = set1.intersection(set2)  
    
    print(set3)

    Output:{56, 23}

    Example – 5: Write the program to add element to the frozenset.

    set1 = {23,44,56,67,90,45,"Javatpoint"}  
    
    set2 = {13,23,56,76,"Sachin"}  
    
    set3 = set1.intersection(set2)  
    
    print(set3)

    Output:TypeError: ‘frozenset’ object does not support item assignment

    Above code raised an error because frozensets are immutable and can’t be changed after creation.

    Example – 6: Write the program to find the issuperset, issubset and superset.

    set1 = set(["Peter","James","Camroon","Ricky","Donald"])  
    
    set2 = set(["Camroon","Washington","Peter"])  
    
    set3 = set(["Peter"])  
    
      
    
    issubset = set1 >= set2  
    
    print(issubset)  
    
    issuperset = set1 <= set2  
    
    print(issuperset)  
    
    issubset = set3 <= set2  
    
    print(issubset)  
    
    issuperset = set2 >= set3  
    
    print(issuperset)

    Output:False False True True


    Python Built-in set methods

    Python contains the following methods to be used with the sets.

    SNMethodDescription
    1add(item)It adds an item to the set. It has no effect if the item is already present in the set.
    2clear()It deletes all the items from the set.
    3copy()It returns a shallow copy of the set.
    4difference_update(….)It modifies this set by removing all the items that are also present in the specified sets.
    5discard(item)It removes the specified item from the set.
    6intersection()It returns a new set that contains only the common elements of both the sets. (all the sets if more than two are specified).
    7intersection_update(….)It removes the items from the original set that are not present in both the sets (all the sets if more than one are specified).
    8Isdisjoint(….)Return True if two sets have a null intersection.
    9Issubset(….)Report whether another set contains this set.
    10Issuperset(….)Report whether this set contains another set.
    11pop()Remove and return an arbitrary set element that is the last element of the set. Raises KeyError if the set is empty.
    12remove(item)Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError.
    13symmetric_difference(….)Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError.
    14symmetric_difference_update(….)Update a set with the symmetric difference of itself and another.
    15union(….)Return the union of sets as a new set.
    (i.e. all elements that are in either set.)
    16update()Update a set with the union of itself and others.
  • Python List Vs Tuple

    This tutorial will study the major differences between lists and tuples and how to handle these two data structures.

    Lists and tuples are types of data structures that hold one or more than one objects or items in a predefined order. We can contain objects of any data type in a list or tuple, including the null data type defined by the None Keyword.

    What is a List?

    In other programming languages, list objects are declared similarly to arrays. Lists don’t have to be homogeneous all the time, so they can simultaneously store items of different data types. This makes lists the most useful tool. The list is a kind of container data Structure of Python that is used to hold numerous pieces of data simultaneously. Lists are helpful when we need to iterate over some elements and keep hold of the items.

    What is a Tuple?

    A tuple is another data structure to store the collection of items of many data types, but unlike mutable lists, tuples are immutable. A tuple, in other words, is a collection of items separated by commas. Because of its static structure, the tuple is more efficient than the list.

    Differences between Lists and Tuples

    In most cases, lists and tuples are equivalent. However, there are some important differences to be explored in this article.

    List and Tuple Syntax Differences

    The syntax of a list differs from that of a tuple. Items of a tuple are enclosed by parentheses or curved brackets (), whereas items of a list are enclosed by square brackets [].

    Example Code

    # Python code to show the difference between creating a list and a tuple  
    
      
    
    list_ = [4, 5, 7, 1, 7]  
    
    tuple_ = (4, 1, 8, 3, 9)  
    
      
    
    print("List is: ", list_)  
    
    print("Tuple is: ", tuple_)

    Output:List is: [4, 5, 7, 1, 7] Tuple is: (4, 1, 8, 3, 9)

    We declared a variable named list_, which contains a certain number of integers ranging from 1 to 10. The list is enclosed in square brackets []. We also created a variable called tuple_, which holds a certain number of integers. The tuple is enclosed in curly brackets (). The type() method in Python returns the data type of the data structure or object passed to it.

    Example Code

    
    
    1. # Code to print the data type of the data structure using the type() function  
    2. print( type(list_) )  
    3. print( type(tuple_) ) 

    Output:<class ‘list’> <class ‘tuple’>

    Mutable List vs. Immutable Tuple

    An important difference between a list and a tuple is that lists are mutable, whereas tuples are immutable. What exactly does this imply? It means a list’s items can be changed or modified, whereas a tuple’s items cannot be changed or modified.

    We can’t employ a list as a key of a dictionary because it is mutable. This is because a key of a Python dictionary is an immutable object. As a result, tuples can be used as keys to a dictionary if required.

    Let’s consider the example highlighting the difference between lists and tuples in immutability and mutability.

    Example Code

    # Updating the element of list and tuple at a particular index  
    
      
    
    # creating a list and a tuple  
    
    list_ = ["Python", "Lists", "Tuples", "Differences"]  
    
    tuple_ = ("Python", "Lists", "Tuples", "Differences")  
    
      
    
    # modifying the last string in both data structures  
    
    list_[3] = "Mutable"  
    
    print( list_ )  
    
    try:  
    
        tuple_[3] = "Immutable"  
    
        print( tuple_ )  
    
    except TypeError:  
    
        print( "Tuples cannot be modified because they are immutable" )

    Output:[‘Python’, ‘Lists’, ‘Tuples’, ‘Mutable’] Tuples cannot be modified because they are immutable

    We altered the string of list_ at index 3 in the above code, which the Python interpreter updated at index 3 in the output. Also, we tried to modify the last index of the tuple in a try block, but since it raised an error, we got output from the except block. This is because tuples are immutable, and the Python interpreter raised TypeError on modifying the tuple.

    Size Difference

    Since tuples are immutable, Python allocates bigger chunks of memory with minimal overhead. Python, on the contrary, allots smaller memory chunks for lists. The tuple would therefore have less memory than the list. If we have a huge number of items, this makes tuples a little more memory-efficient than lists.

    For example, consider creating a list and a tuple with the identical items and comparing their sizes:

    Example Code

    # Code to show the difference in the size of a list and a tuple  
    
      
    
    #creating a list and a tuple  
    
    list_ = ["Python", "Lists", "Tuples", "Differences"]  
    
    tuple_ = ("Python", "Lists", "Tuples", "Differences")  
    
    # printing sizes   
    
    print("Size of tuple: ", tuple_.__sizeof__())  
    
    print("Size of list: ", list_.__sizeof__())

    Output:Size of tuple: 28 Size of list: 52

    Available Functions

    Tuples have fewer built-in functions than lists. We may leverage the in-built function dir([object] to access all the corresponding methods for the list and tuple.

    Example Code

    # printing directory of list  
    
    dir(list_)

    Output:[‘__add__’, ‘__class__’, ‘__class_getitem__’, ‘__contains__’, ‘__delattr__’, ‘__delitem__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__gt__’, ‘__hash__’, ‘__iadd__’, ‘__imul__’, ‘__init__’, ‘__init_subclass__’, ‘__iter__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__mul__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__reversed__’, ‘__rmul__’, ‘__setattr__’, ‘__setitem__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘append’, ‘clear’, ‘copy’, ‘count’, ‘extend’, ‘index’, ‘insert’, ‘pop’, ‘remove’, ‘reverse’, ‘sort’]

    Example Code

    # Printing directory of a tuple  
    
    print( dir(tuple_), end = ", " )

    Output:[‘__add__’, ‘__class__’, ‘__class_getitem__’, ‘__contains__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__getnewargs__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__iter__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__mul__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__rmul__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘count’, ‘index’]

    As we can observe, a list has many more methods than a tuple. With intrinsic functions, we can perform insert and pop operations and remove and sort items from the list not provided in the tuple.

    Tuples and Lists: Key Similarities

    • They both hold collections of items and are heterogeneous data types, meaning they can contain multiple data types simultaneously.
    • They’re both ordered, which implies the items or objects are maintained in the same order as they were placed until changed manually.
    • Because they’re both sequential data structures, we can iterate through the objects they hold; hence, they are iterables.
    • An integer index, enclosed in square brackets [index], can be used to access objects of both data types.
  • Python Tuples

    A comma-separated group of items is called a Python triple. The ordering, settled items, and reiterations of a tuple are to some degree like those of a rundown, but in contrast to a rundown, a tuple is unchanging.

    The main difference between the two is that we cannot alter the components of a tuple once they have been assigned. On the other hand, we can edit the contents of a list.

    Example

    1. (“Suzuki”, “Audi”, “BMW”,” Skoda “) is a tuple.  

    Features of Python Tuple

    • Tuples are an immutable data type, meaning their elements cannot be changed after they are generated.
    • Each element in a tuple has a specific order that will never change because tuples are ordered sequences.

    Forming a Tuple:

    All the objects-also known as “elements”-must be separated by a comma, enclosed in parenthesis (). Although parentheses are not required, they are recommended.

    Any number of items, including those with various data types (dictionary, string, float, list, etc.), can be contained in a tuple.

    Code

    # Python program to show how to create a tuple    
    
    # Creating an empty tuple    
    
    empty_tuple = ()    
    
    print("Empty tuple: ", empty_tuple)    
    
        
    
    # Creating tuple having integers    
    
    int_tuple = (4, 6, 8, 10, 12, 14)    
    
    print("Tuple with integers: ", int_tuple)    
    
        
    
    # Creating a tuple having objects of different data types    
    
    mixed_tuple = (4, "Python", 9.3)    
    
    print("Tuple with different data types: ", mixed_tuple)    
    
        
    
    # Creating a nested tuple    
    
    nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))    
    
    print("A nested tuple: ", nested_tuple)

    Output:Empty tuple: () Tuple with integers: (4, 6, 8, 10, 12, 14) Tuple with different data types: (4, ‘Python’, 9.3) A nested tuple: (‘Python’, {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))

    Parentheses are not necessary for the construction of multiples. This is known as triple pressing.

    Code

    # Python program to create a tuple without using parentheses    
    
    # Creating a tuple    
    
    tuple_ = 4, 5.7, "Tuples", ["Python", "Tuples"]    
    
    # Displaying the tuple created    
    
    print(tuple_)    
    
    # Checking the data type of object tuple_    
    
    print(type(tuple_) )    
    
    # Trying to modify tuple_    
    
    try:    
    
        tuple_[1] = 4.2    
    
    except:    
    
        print(TypeError )

    Output:(4, 5.7, ‘Tuples’, [‘Python’, ‘Tuples’]) <class ‘tuple’> <class ‘TypeError’>

    The development of a tuple from a solitary part may be complex.

    Essentially adding a bracket around the component is lacking. A comma must separate the element to be recognized as a tuple.

    Code

    # Python program to show how to create a tuple having a single element    
    
    single_tuple = ("Tuple")    
    
    print( type(single_tuple) )     
    
    # Creating a tuple that has only one element    
    
    single_tuple = ("Tuple",)    
    
    print( type(single_tuple) )     
    
    # Creating tuple without parentheses    
    
    single_tuple = "Tuple",    
    
    print( type(single_tuple) )

    Output:<class ‘str’> <class ‘tuple’> <class ‘tuple’>

    Accessing Tuple Elements

    A tuple’s objects can be accessed in a variety of ways.

    Indexing

    Indexing We can use the index operator [] to access an object in a tuple, where the index starts at 0.

    The indices of a tuple with five items will range from 0 to 4. An Index Error will be raised assuming we attempt to get to a list from the Tuple that is outside the scope of the tuple record. An index above four will be out of range in this scenario.

    Because the index in Python must be an integer, we cannot provide an index of a floating data type or any other type. If we provide a floating index, the result will be TypeError.

    The method by which elements can be accessed through nested tuples can be seen in the example below.

    Code

    # Python program to show how to access tuple elements    
    
    # Creating a tuple    
    
    tuple_ = ("Python", "Tuple", "Ordered", "Collection")    
    
    print(tuple_[0])      
    
    print(tuple_[1])     
    
    # trying to access element index more than the length of a tuple    
    
    try:    
    
        print(tuple_[5])     
    
    except Exception as e:    
    
        print(e)    
    
    # trying to access elements through the index of floating data type    
    
    try:    
    
        print(tuple_[1.0])     
    
    except Exception as e:    
    
        print(e)    
    
    # Creating a nested tuple    
    
    nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7))    
    
        
    
    # Accessing the index of a nested tuple    
    
    print(nested_tuple[0][3])           
    
    print(nested_tuple[1][1])

    Output:Python Tuple tuple index out of range tuple indices must be integers or slices, not float l 6

    • Negative Indexing

    Python’s sequence objects support negative indexing.

    The last thing of the assortment is addressed by – 1, the second last thing by – 2, etc.

    Code

    # Python program to show how negative indexing works in Python tuples    
    
    # Creating a tuple    
    
    tuple_ = ("Python", "Tuple", "Ordered", "Collection")    
    
    # Printing elements using negative indices    
    
    print("Element at -1 index: ", tuple_[-1])    
    
    print("Elements between -4 and -1 are: ", tuple_[-4:-1])

    Output:Element at -1 index: Collection Elements between -4 and -1 are: (‘Python’, ‘Tuple’, ‘Ordered’)

    Slicing

    Tuple slicing is a common practice in Python and the most common way for programmers to deal with practical issues. Look at a tuple in Python. Slice a tuple to access a variety of its elements. Using the colon as a straightforward slicing operator (:) is one strategy.

    To gain access to various tuple elements, we can use the slicing operator colon (:).

    Code

    # Python program to show how slicing works in Python tuples    
    
    # Creating a tuple    
    
    tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")    
    
    # Using slicing to access elements of the tuple    
    
    print("Elements between indices 1 and 3: ", tuple_[1:3])    
    
    # Using negative indexing in slicing    
    
    print("Elements between indices 0 and -4: ", tuple_[:-4])    
    
    # Printing the entire tuple by using the default start and end values.     
    
    print("Entire tuple: ", tuple_[:])

    Output:Elements between indices 1 and 3: (‘Tuple’, ‘Ordered’) Elements between indices 0 and -4: (‘Python’, ‘Tuple’) Entire tuple: (‘Python’, ‘Tuple’, ‘Ordered’, ‘Immutable’, ‘Collection’, ‘Objects’)

    Deleting a Tuple

    A tuple’s parts can’t be modified, as was recently said. We are unable to eliminate or remove tuple components as a result.

    However, the keyword del can completely delete a tuple.

    Code

    # Python program to show how to delete elements of a Python tuple    
    
    # Creating a tuple    
    
    tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")    
    
    # Deleting a particular element of the tuple    
    
    try:     
    
        del tuple_[3]    
    
        print(tuple_)    
    
    except Exception as e:    
    
        print(e)    
    
    # Deleting the variable from the global space of the program    
    
    del tuple_    
    
    # Trying accessing the tuple after deleting it    
    
    try:    
    
        print(tuple_)    
    
    except Exception as e:    
    
        print(e)

    Output:‘tuple’ object does not support item deletion name ‘tuple_’ is not defined

    Repetition Tuples in Python

    Code

    # Python program to show repetition in tuples    
    
    tuple_ = ('Python',"Tuples")    
    
    print("Original tuple is: ", tuple_)    
    
    # Repeting the tuple elements    
    
    tuple_ = tuple_ * 3    
    
    print("New tuple is: ", tuple_)

    Output:Original tuple is: (‘Python’, ‘Tuples’) New tuple is: (‘Python’, ‘Tuples’, ‘Python’, ‘Tuples’, ‘Python’, ‘Tuples’)

    Tuple Methods

    Like the list, Python Tuples is a collection of immutable objects. There are a few ways to work with tuples in Python. With some examples, this essay will go over these two approaches in detail.

    The following are some examples of these methods.

    • Count () Method

    The times the predetermined component happens in the Tuple is returned by the count () capability of the Tuple.

    Code

    # Creating tuples  
    
    T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)  
    
    T2 = ('python', 'java', 'python', 'Tpoint', 'python', 'java')  
    
    # counting the appearance of 3  
    
    res = T1.count(2)  
    
    print('Count of 2 in T1 is:', res)  
    
    # counting the appearance of java  
    
    res = T2.count('java')  
    
    print('Count of Java in T2 is:', res)

    Output:Count of 2 in T1 is: 5 Count of java in T2 is: 2

    Index() Method:

    The Index() function returns the first instance of the requested element from the Tuple.

    Parameters:

    • The thing that must be looked for.
    • Start: (Optional) the index that is used to begin the final (optional) search: The most recent index from which the search is carried out
    • Index Method

    Code

    # Creating tuples  
    
    Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)  
    
    # getting the index of 3  
    
    res = Tuple_data.index(3)  
    
    print('First occurrence of 1 is', res)  
    
    # getting the index of 3 after 4th  
    
    # index  
    
    res = Tuple_data.index(3, 4)  
    
    print('First occurrence of 1 after 4th index is:', res)

    Output:First occurrence of 1 is 2 First occurrence of 1 after 4th index is: 6

    Tuple Membership Test

    Utilizing the watchword, we can decide whether a thing is available in the given Tuple.

    Code

    # Python program to show how to perform membership test for tuples    
    
    # Creating a tuple    
    
    tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordered")    
    
    # In operator    
    
    print('Tuple' in tuple_)    
    
    print('Items' in tuple_)    
    
    # Not in operator    
    
    print('Immutable' not in tuple_)    
    
    print('Items' not in tuple_)

    Output:True False False True

    Iterating Through a Tuple

    A for loop can be used to iterate through each tuple element.

    Code

    # Python program to show how to iterate over tuple elements    
    
    # Creating a tuple    
    
    tuple_ = ("Python", "Tuple", "Ordered", "Immutable")    
    
    # Iterating over tuple elements using a for loop    
    
    for item in tuple_:    
    
        print(item)

    Output:Python Tuple Ordered Immutable

    Changing a Tuple

    Tuples, instead of records, are permanent articles.

    This suggests that once the elements of a tuple have been defined, we cannot change them. However, the nested elements can be altered if the element itself is a changeable data type like a list.

    Multiple values can be assigned to a tuple through reassignment.

    Code

    # Python program to show that Python tuples are immutable objects    
    
    # Creating a tuple    
    
    tuple_ = ("Python", "Tuple", "Ordered", "Immutable", [1,2,3,4])    
    
    # Trying to change the element at index 2    
    
    try:    
    
        tuple_[2] = "Items"    
    
        print(tuple_)    
    
    except Exception as e:    
    
        print( e )    
    
    # But inside a tuple, we can change elements of a mutable object    
    
    tuple_[-1][2] = 10     
    
    print(tuple_)    
    
    # Changing the whole tuple    
    
    tuple_ = ("Python", "Items")    
    
    print(tuple_)

    Output:‘tuple’ object does not support item assignment (‘Python’, ‘Tuple’, ‘Ordered’, ‘Immutable’, [1, 2, 10, 4]) (‘Python’, ‘Items’)

    The + operator can be used to combine multiple tuples into one. This phenomenon is known as concatenation.

    We can also repeat the elements of a tuple a predetermined number of times by using the * operator. This is already demonstrated above.

    The aftereffects of the tasks + and * are new tuples.

    Code

    # Python program to show how to concatenate tuples    
    
    # Creating a tuple    
    
    tuple_ = ("Python", "Tuple", "Ordered", "Immutable")    
    
    # Adding a tuple to the tuple_    
    
    print(tuple_ + (4, 5, 6))

    Output:(‘Python’, ‘Tuple’, ‘Ordered’, ‘Immutable’, 4, 5, 6)

    Tuples have the following advantages over lists:

    • Triples take less time than lists do.
    • Due to tuples, the code is protected from accidental modifications. It is desirable to store non-changing information in “tuples” instead of “records” if a program expects it.
    • A tuple can be used as a dictionary key if it contains immutable values like strings, numbers, or another tuple. “Lists” cannot be utilized as dictionary keys because they are mutable.
  • Python List

    In Python, the sequence of various data types is stored in a list. A list is a collection of different kinds of values or items. Since Python lists are mutable, we can change their elements after forming. The comma (,) and the square brackets [enclose the List’s items] serve as separators.

    Although six Python data types can hold sequences, the List is the most common and reliable form. A list, a type of sequence data, is used to store the collection of data. Tuples and Strings are two similar data formats for sequences.

    Lists written in Python are identical to dynamically scaled arrays defined in other languages, such as Array List in Java and Vector in C++. A list is a collection of items separated by commas and denoted by the symbol [].

    List Declaration

    Code

    
    
    1. # a simple list   
    2. list1 = [1, 2, "Python", "Program", 15.9]      
    3. list2 = ["Amy", "Ryan", "Henry", "Emma"]   
    4.   
    5. # printing the list  
    6. print(list1)  
    7. print(list2)  
    8.   
    9. # printing the type of list  
    10. print(type(list1))  
    11. print(type(list2))  

    Output:[1, 2, ‘Python’, ‘Program’, 15.9] [‘Amy’, ‘Ryan’, ‘Henry’, ‘Emma’] < class ‘ list ‘ > < class ‘ list ‘ >

    Characteristics of Lists

    The characteristics of the List are as follows:

    • The lists are in order.
    • The list element can be accessed via the index.
    • The mutable type of List is
    • The rundowns are changeable sorts.
    • The number of various elements can be stored in a list.

    Ordered List Checking

    Code

    # example  
    
    a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]    
    
    b = [ 1, 2, 5, "Ram", 3.50, "Rahul", 6 ]    
    
    a == b

    Output:False

    The indistinguishable components were remembered for the two records; however, the subsequent rundown changed the file position of the fifth component, which is against the rundowns’ planned request. False is returned when the two lists are compared.

    Code

    # example  
    
    a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]    
    
    b = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]    
    
    a == b

    Output:True

    Records forever protect the component’s structure. Because of this, it is an arranged collection of things.

    Let’s take a closer look at the list example.

    Code

    # list example in detail  
    
    emp = [ "John", 102, "USA"]       
    
    Dep1 = [ "CS",10]    
    
    Dep2 = [ "IT",11]      
    
    HOD_CS = [ 10,"Mr. Holding"]      
    
    HOD_IT = [11, "Mr. Bewon"]      
    
    print("printing employee data ...")      
    
    print(" Name : %s, ID: %d, Country: %s" %(emp[0], emp[1], emp[2]))      
    
    print("printing departments ...")     
    
    print("Department 1:\nName: %s, ID: %d\n Department 2:\n Name: %s, ID: %s"%( Dep1[0], Dep2[1], Dep2[0], Dep2[1]))      
    
    print("HOD Details ....")      
    
    print("CS HOD Name: %s, Id: %d" %(HOD_CS[1], HOD_CS[0]))      
    
    print("IT HOD Name: %s, Id: %d" %(HOD_IT[1], HOD_IT[0]))      
    
    print(type(emp), type(Dep1), type(Dep2), type(HOD_CS), type(HOD_IT))

    Output:printing employee data… Name : John, ID: 102, Country: USA printing departments… Department 1: Name: CS, ID: 11 Department 2: Name: IT, ID: 11 HOD Details …. CS HOD Name: Mr. Holding, Id: 10 IT HOD Name: Mr. Bewon, Id: 11 <class ‘ list ‘> <class ‘ list ‘> <class ‘ list ‘> <class ‘ list ‘> <class ‘ list ‘>

    In the preceding illustration, we printed the employee and department-specific details from lists that we had created. To better comprehend the List’s concept, look at the code above.

    List Indexing and Splitting

    The indexing procedure is carried out similarly to string processing. The slice operator [] can be used to get to the List’s components.

    The index ranges from 0 to length -1. The 0th index is where the List’s first element is stored; the 1st index is where the second element is stored, and so on.

    Python List

    We can get the sub-list of the list using the following syntax.

    1. list_varible(start:stop:step)    
    • The beginning indicates the beginning record position of the rundown.
    • The stop signifies the last record position of the rundown.
    • Within a start, the step is used to skip the nth element: stop.

    The start parameter is the initial index, the step is the ending index, and the value of the end parameter is the number of elements that are “stepped” through. The default value for the step is one without a specific value. Inside the resultant Sub List, the same with record start would be available, yet the one with the file finish will not. The first element in a list appears to have an index of zero.

    Consider the following example:

    Code

    list = [1,2,3,4,5,6,7]    
    
    print(list[0])    
    
    print(list[1])    
    
    print(list[2])    
    
    print(list[3])    
    
    # Slicing the elements    
    
    print(list[0:6])    
    
    # By default, the index value is 0 so its starts from the 0th element and go for index -1.    
    
    print(list[:])    
    
    print(list[2:5])    
    
    print(list[1:6:2])

    Output:1 2 3 4 [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6, 7] [3, 4, 5] [2, 4, 6]

    In contrast to other programming languages, Python lets you use negative indexing as well. The negative indices are counted from the right. The index -1 represents the final element on the List’s right side, followed by the index -2 for the next member on the left, and so on, until the last element on the left is reached.

    Python List

    Let’s have a look at the following example where we will use negative indexing to access the elements of the list.

    Code

    # negative indexing example  
    
    list = [1,2,3,4,5]    
    
    print(list[-1])    
    
    print(list[-3:])    
    
    print(list[:-1])    
    
    print(list[-3:-1])

    Output:5 [3, 4, 5] [1, 2, 3, 4] [3, 4]

    Negative indexing allows us to obtain an element, as previously mentioned. The rightmost item in the List was returned by the first print statement in the code above. The second print statement returned the sub-list, and so on.

    Updating List Values

    Due to their mutability and the slice and assignment operator’s ability to update their values, lists are Python’s most adaptable data structure. Python’s append() and insert() methods can also add values to a list.

    Consider the following example to update the values inside the List.

    Code

    
    
    1. # updating list values  
    2. list = [1, 2, 3, 4, 5, 6]       
    3. print(list)       
    4. # It will assign value to the value to the second index     
    5. list[2] = 10     
    6. print(list)      
    7. # Adding multiple-element     
    8. list[1:3] = [89, 78]       
    9. print(list)     
    10. # It will add value at the end of the list    
    11. list[-1] = 25    
    12. print(list)

    Output:[1, 2, 3, 4, 5, 6] [1, 2, 10, 4, 5, 6] [1, 89, 78, 4, 5, 6] [1, 89, 78, 4, 5, 25]

    The list elements can also be deleted by using the del keyword. Python also provides us the remove() method if we do not know which element is to be deleted from the list.

    Consider the following example to delete the list elements.

    Code

    list = [1, 2, 3, 4, 5, 6]       
    
    print(list)       
    
    # It will assign value to the value to second index     
    
    list[2] = 10     
    
    print(list)      
    
    # Adding multiple element     
    
    list[1:3] = [89, 78]       
    
    print(list)     
    
    # It will add value at the end of the list    
    
    list[-1] = 25    
    
    print(list)

    Output:[1, 2, 3, 4, 5, 6] [1, 2, 10, 4, 5, 6] [1, 89, 78, 4, 5, 6] [1, 89, 78, 4, 5, 25]

    Python List Operations

    Repetition
    
    Concatenation
    
    Length
    
    Iteration
    
    Membership

    Let’s see how the list responds to various operators.

    1. Repetition

    The redundancy administrator empowers the rundown components to be rehashed on different occasions.

    Code

    # repetition of list  
    
    # declaring the list  
    
    list1 = [12, 14, 16, 18, 20]  
    
    # repetition operator *  
    
    l = list1 * 2  
    
    print(l)

    Output:[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]

    2. Concatenation

    It concatenates the list mentioned on either side of the operator.

    Code

    # concatenation of two lists  
    
    # declaring the lists  
    
    list1 = [12, 14, 16, 18, 20]  
    
    list2 = [9, 10, 32, 54, 86]  
    
    # concatenation operator +  
    
    l = list1 + list2  
    
    print(l)

    Output:[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]

    3. Length

    It is used to get the length of the list

    Code

    1. # size of the list  
    2. # declaring the list  
    3. list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]  
    4. # finding length of the list  
    5. len(list1)  

    Output:9

    4. Iteration

    The for loop is used to iterate over the list elements.

    Code

    
    
    1. # iteration of the list  
    2. # declaring the list  
    3. list1 = [12, 14, 16, 39, 40]  
    4. # iterating  
    5. for i in list1:   
    6.     print(i)  

    Output:12 14 16 39 40

    5. Membership

    It returns true if a particular item exists in a particular list otherwise false.

    Code

    # membership of the list  
    
    # declaring the list  
    
    list1 = [100, 200, 300, 400, 500]  
    
    # true will be printed if value exists  
    
    # and false if not  
    
      
    
    print(600 in list1)  
    
    print(700 in list1)  
    
    print(1040 in list1)  
    
      
    
    print(300 in list1)  
    
    print(100 in list1)  
    
    print(500 in list1)

    Output:False False False True True True

    Iterating a List

    A list can be iterated by using a for – in loop. A simple list containing four strings, which can be iterated as follows.

    Code

    
    
    1. # iterating a list  
    2. list = ["John", "David", "James", "Jonathan"]      
    3. for i in list:     
    4.     # The i variable will iterate over the elements of the List and contains each element in each iteration.       
    5.     print(i)  

    Output:John David James Jonathan

    Adding Elements to the List

    The append() function in Python can add a new item to the List. In any case, the annex() capability can enhance the finish of the rundown.

    Consider the accompanying model, where we take the components of the rundown from the client and print the rundown on the control center.

    Code

    
    
    1. #Declaring the empty list    
    2. l =[]    
    3. #Number of elements will be entered by the user      
    4. n = int(input("Enter the number of elements in the list:"))    
    5. # for loop to take the input    
    6. for i in range(0,n):       
    7.     # The input is taken from the user and added to the list as the item    
    8.     l.append(input("Enter the item:"))       
    9. print("printing the list items..")     
    10. # traversal loop to print the list items      
    11. for i in l:     
    12.     print(i, end = "  ")   

    Output:Enter the number of elements in the list:10 Enter the item:32 Enter the item:56 Enter the item:81 Enter the item:2 Enter the item:34 Enter the item:65 Enter the item:09 Enter the item:66 Enter the item:12 Enter the item:18 printing the list items.. 32 56 81 2 34 65 09 66 12 18

    Removing Elements from the List

    The remove() function in Python can remove an element from the List. To comprehend this idea, look at the example that follows.

    Example –

    Code

    list = [0,1,2,3,4]       
    
    print("printing original list: ");      
    
    for i in list:      
    
        print(i,end=" ")      
    
    list.remove(2)      
    
    print("\nprinting the list after the removal of first element...")      
    
    for i in list:      
    
        print(i,end=" ")

    Output:printing original list: 0 1 2 3 4 printing the list after the removal of first element… 0 1 3 4

    Python List Built-in Functions

    Python provides the following built-in functions, which can be used with the lists.

    1. len()
    2. max()
    3. min()

    len( )

    It is used to calculate the length of the list.

    Code

    # size of the list  
    
    # declaring the list  
    
    list1 = [12, 16, 18, 20, 39, 40]  
    
    # finding length of the list  
    
    len(list1)

    Output:6

    Max( )

    It returns the maximum element of the list

    Code

    # maximum of the list  
    
    list1 = [103, 675, 321, 782, 200]  
    
    # large element in the list  
    
    print(max(list1))

    Output:782

    Min( )

    It returns the minimum element of the list

    Code

    
    
    1. # minimum of the list  
    2. list1 = [103, 675, 321, 782, 200]  
    3. # smallest element in the list  
    4. print(min(list1))  

    Output:103

    Let’s have a look at the few list examples.

    Example: 1- Create a program to eliminate the List’s duplicate items.

    Code

    list1 = [1,2,2,3,55,98,65,65,13,29]    
    
    # Declare an empty list that will store unique values    
    
    list2 = []    
    
    for i in list1:    
    
        if i not in list2:    
    
            list2.append(i)    
    
    print(list2)

    Output:[1, 2, 3, 55, 98, 65, 13, 29]

    Example:2- Compose a program to track down the amount of the component in the rundown.

    Code

    list1 = [3,4,5,9,10,12,24]    
    
    sum = 0    
    
    for i in list1:    
    
        sum = sum+i        
    
    print("The sum is:",sum)

    Output:The sum is: 67 In [8]:

    Example: 3- Compose the program to find the rundowns comprise of somewhere around one normal component.

    Code

    
    
    1. list1 = [1,2,3,4,5,6]    
    2. list2 = [7,8,9,2,10]    
    3. for x in list1:    
    4.     for y in list2:    
    5.         if x == y:    
    6.             print("The common element is:",x)  

    Output:The common element is: 2

  • Python String

    Till now, we have discussed numbers as the standard data-types in Python. In this section of the tutorial, we will discuss the most popular data type in Python, i.e., string.

    Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes. The computer does not understand the characters; internally, it stores manipulated character as the combination of the 0’s and 1’s.

    Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are also called the collection of Unicode characters.

    In Python, strings can be created by enclosing the character or the sequence of characters in the quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the string.

    Consider the following example in Python to create a string.

    Syntax:

    str = "Hi Python !"    

    Here, if we check the type of the variable str using a Python script

    1. print(type(str)), then it will print a string (str).    

    In Python, strings are treated as the sequence of characters, which means that Python doesn’t support the character data-type; instead, a single character written as ‘p’ is treated as the string of length 1.

    Creating String in Python

    We can create a string by enclosing the characters in single-quotes or double- quotes. Python also provides triple-quotes to represent the string, but it is generally used for multiline string or docstrings.

    #Using single quotes  
    
    str1 = 'Hello Python'  
    
    print(str1)  
    
    #Using double quotes  
    
    str2 = "Hello Python"  
    
    print(str2)  
    
      
    
    #Using triple quotes  
    
    str3 = '''''Triple quotes are generally used for  
    
        represent the multiline or 
    
        docstring'''   
    
    print(str3)

    Output:Hello Python Hello Python Triple quotes are generally used for represent the multiline or docstring

    Strings indexing and splitting

    Like other languages, the indexing of the Python strings starts from 0. For example, The string “HELLO” is indexed as given in the below figure.

    Python String

    Consider the following example:

    str = "HELLO"  
    
    print(str[0])  
    
    print(str[1])  
    
    print(str[2])  
    
    print(str[3])  
    
    print(str[4])  
    
    # It returns the IndexError because 6th index doesn't exist  
    
    print(str[6])

    Output:H E L L O IndexError: string index out of range

    As shown in Python, the slice operator [] is used to access the individual characters of the string. However, we can use the : (colon) operator in Python to access the substring from the given string. Consider the following example.

    Python String

    Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if str = ‘HELLO’ is given, then str[1:3] will always include str[1] = ‘E’, str[2] = ‘L’ and nothing else.

    Consider the following example:

    # Given String  
    
    str = "JAVATPOINT"  
    
    # Start Oth index to end  
    
    print(str[0:])  
    
    # Starts 1th index to 4th index  
    
    print(str[1:5])  
    
    # Starts 2nd index to 3rd index  
    
    print(str[2:4])  
    
    # Starts 0th to 2nd index  
    
    print(str[:3])  
    
    #Starts 4th to 6th index  
    
    print(str[4:7])

    Output:JAVATPOINT AVAT VA JAV TPO

    We can do the negative slicing in the string; it starts from the rightmost character, which is indicated as -1. The second rightmost index indicates -2, and so on. Consider the following image.

    Python String

    Consider the following example

    str = 'JAVATPOINT'  
    
    print(str[-1])  
    
    print(str[-3])  
    
    print(str[-2:])  
    
    print(str[-4:-1])  
    
    print(str[-7:-2])  
    
    # Reversing the given string  
    
    print(str[::-1])  
    
    print(str[-12])

    Output:T I NT OIN ATPOI TNIOPTAVAJ IndexError: string index out of range

    Reassigning Strings

    Updating the content of the strings is as easy as assigning it to a new string. The string object doesn’t support item assignment i.e., A string can only be replaced with new string since its content cannot be partially replaced. Strings are immutable in Python.

    Consider the following example.

    Example 1

    str = "HELLO"    
    
    str[0] = "h"    
    
    print(str)

    Output:Traceback (most recent call last): File “12.py”, line 2, in <module> str[0] = “h”; TypeError: ‘str’ object does not support item assignment

    However, in example 1, the string str can be assigned completely to a new content as specified in the following example.

    Example 2

    str = "HELLO"    
    
    print(str)    
    
    str = "hello"    
    
    print(str)

    Output:HELLO hello

    Deleting the String

    As we know that strings are immutable. We cannot delete or remove the characters from the string.  But we can delete the entire string using the del keyword.

    str = "Foobrdigital"  
    
    del str[1]

    Output:TypeError: ‘str’ object doesn’t support item deletion

    Now we are deleting entire string.

    str1 = "Foobrdigital"  
    
    del str1  
    
    print(str1)

    Output:NameError: name ‘str1’ is not defined

    String Operators

    OperatorDescription
    +It is known as concatenation operator used to join the strings given either side of the operator.
    *It is known as repetition operator. It concatenates the multiple copies of the same string.
    []It is known as slice operator. It is used to access the sub-strings of a particular string.
    [:]It is known as range slice operator. It is used to access the characters from the specified range.
    inIt is known as membership operator. It returns if a particular sub-string is present in the specified string.
    not inIt is also a membership operator and does the exact reverse of in. It returns true if a particular substring is not present in the specified string.
    r/RIt is used to specify the raw string. Raw strings are used in the cases where we need to print the actual meaning of escape characters such as “C://python”. To define any string as a raw string, the character r or R is followed by the string.
    %It is used to perform string formatting. It makes use of the format specifiers used in C programming like %d or %f to map their values in python. We will discuss how formatting is done in python.

    Example

    Consider the following example to understand the real use of Python operators.

    str = "Hello"     
    
    str1 = " world"    
    
    print(str*3) # prints HelloHelloHello    
    
    print(str+str1)# prints Hello world     
    
    print(str[4]) # prints o                
    
    print(str[2:4]); # prints ll                    
    
    print('w' in str) # prints false as w is not present in str    
    
    print('wo' not in str1) # prints false as wo is present in str1.     
    
    print(r'C://python37') # prints C://python37 as it is written    
    
    print("The string str : %s"%(str)) # prints The string str : Hello

    Output:HelloHelloHello Hello world o ll False False C://python37 The string str : Hello

    Python String Formatting

    Escape Sequence

    Let’s suppose we need to write the text as – They said, “Hello what’s going on?”- the given statement can be written in single quotes or double quotes but it will raise the SyntaxError as it contains both single and double-quotes.

    Example

    Consider the following example to understand the real use of Python operators.

    str = "They said, "Hello what's going on?""  
    
    print(str)

    Output:SyntaxError: invalid syntax

    We can use the triple quotes to accomplish this problem but Python provides the escape sequence.

    The backslash(/) symbol denotes the escape sequence. The backslash can be followed by a special character and it interpreted differently. The single quotes inside the string must be escaped. We can apply the same as in the double quotes.

    Example –

    # using triple quotes  
    
    print('''''They said, "What's there?"''')  
    
      
    
    # escaping single quotes  
    
    print('They said, "What\'s going on?"')  
    
      
    
    # escaping double quotes  
    
    print("They said, \"What's going on?\"")

    Output:They said, “What’s there?” They said, “What’s going on?” They said, “What’s going on?”

    The list of an escape sequence is given below:

    Sr.Escape SequenceDescriptionExample
    1.\newlineIt ignores the new line.print(“Python1 \ Python2 \ Python3”)Output:Python1 Python2 Python3
    2.\\Backslashprint(“\\”)Output:\
    3.\’Single Quotesprint(‘\”)Output:
    4.\\”Double Quotesprint(“\””)Output:
    5.\aASCII Bellprint(“\a”)
    6.\bASCII Backspace(BS)print(“Hello \b World”)Output:Hello World
    7.\fASCII Formfeedprint(“Hello \f World!”) Hello World!
    8.\nASCII Linefeedprint(“Hello \n World!”)Output:Hello World!
    9.\rASCII Carriege Return(CR)print(“Hello \r World!”)Output:World!
    10.\tASCII Horizontal Tabprint(“Hello \t World!”)Output:Hello World!
    11.\vASCII Vertical Tabprint(“Hello \v World!”)Output:Hello World!
    12.\oooCharacter with octal valueprint(“\110\145\154\154\157”)Output: Hello
    13\xHHCharacter with hex value.print(“\x48\x65\x6c\x6c\x6f”)Output:Hello

    Here is the simple example of escape sequence.

    print("C:\\Users\\DEVANSH SHARMA\\Python32\\Lib")  
    
    print("This is the \n multiline quotes")  
    
    print("This is \x48\x45\x58 representation")

    Output:C:\Users\DEVANSH SHARMA\Python32\Lib This is the multiline quotes This is HEX representation

    We can ignore the escape sequence from the given string by using the raw string. We can do this by writing r or R in front of the string. Consider the following example.

    1. print(r”C:\\Users\\DEVANSH SHARMA\\Python32″)  

    Output:C:\\Users\\DEVANSH SHARMA\\Python32

    The format() method

    The format() method is the most flexible and useful method in formatting strings. The curly braces {} are used as the placeholder in the string and replaced by the format() method argument. Let’s have a look at the given an example:

    # Using Curly braces  
    
    print("{} and {} both are the best friend".format("Devansh","Abhishek"))  
    
      
    
    #Positional Argument  
    
    print("{1} and {0} best players ".format("Virat","Rohit"))  
    
      
    
    #Keyword Argument  
    
    print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))

    Output:Devansh and Abhishek both are the best friend Rohit and Virat best players James,Peter,Ricky

    Python String Formatting Using % Operator

    Python allows us to use the format specifiers used in C’s printf statement. The format specifiers in Python are treated in the same way as they are treated in C. However, Python provides an additional operator %, which is used as an interface between the format specifiers and their values. In other words, we can say that it binds the format specifiers to the values.

    Consider the following example.

    Integer = 10;    
    
    Float = 1.290    
    
    String = "Devansh"    
    
    print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am string ... My value is %s"%(Integer,Float,String))

    Output:Hi I am Integer … My value is 10 Hi I am float … My value is 1.290000 Hi I am string … My value is Devansh


    Python String functions

    Python provides various in-built functions that are used for string handling. Many String fun

    MethodDescription
    capitalize()It capitalizes the first character of the String. This function is deprecated in python3
    casefold()It returns a version of s suitable for case-less comparisons.
    center(width ,fillchar)It returns a space padded string with the original string centred with equal number of left and right spaces.
    count(string,begin,end)It counts the number of occurrences of a substring in a String between begin and end index.
    decode(encoding = ‘UTF8’, errors = ‘strict’)Decodes the string using codec registered for encoding.
    encode()Encode S using the codec registered for encoding. Default encoding is ‘utf-8’.
    endswith(suffix ,begin=0,end=len(string))It returns a Boolean value if the string terminates with given suffix between begin and end.
    expandtabs(tabsize = 8)It defines tabs in string to multiple spaces. The default space value is 8.
    find(substring ,beginIndex, endIndex)It returns the index value of the string where substring is found between begin index and end index.
    format(value)It returns a formatted version of S, using the passed value.
    index(subsring, beginIndex, endIndex)It throws an exception if string is not found. It works same as find() method.
    isalnum()It returns true if the characters in the string are alphanumeric i.e., alphabets or numbers and there is at least 1 character. Otherwise, it returns false.
    isalpha()It returns true if all the characters are alphabets and there is at least one character, otherwise False.
    isdecimal()It returns true if all the characters of the string are decimals.
    isdigit()It returns true if all the characters are digits and there is at least one character, otherwise False.
    isidentifier()It returns true if the string is the valid identifier.
    islower()It returns true if the characters of a string are in lower case, otherwise false.
    isnumeric()It returns true if the string contains only numeric characters.
    isprintable()It returns true if all the characters of s are printable or s is empty, false otherwise.
    isupper()It returns false if characters of a string are in Upper case, otherwise False.
    isspace()It returns true if the characters of a string are white-space, otherwise false.
    istitle()It returns true if the string is titled properly and false otherwise. A title string is the one in which the first character is upper-case whereas the other characters are lower-case.
    isupper()It returns true if all the characters of the string(if exists) is true otherwise it returns false.
    join(seq)It merges the strings representation of the given sequence.
    len(string)It returns the length of a string.
    ljust(width[,fillchar])It returns the space padded strings with the original string left justified to the given width.
    lower()It converts all the characters of a string to Lower case.
    lstrip()It removes all leading whitespaces of a string and can also be used to remove particular character from leading.
    partition()It searches for the separator sep in S, and returns the part before it, the separator itself, and the part after it. If the separator is not found, return S and two empty strings.
    maketrans()It returns a translation table to be used in translate function.
    replace(old,new[,count])It replaces the old sequence of characters with the new sequence. The max characters are replaced if max is given.
    rfind(str,beg=0,end=len(str))It is similar to find but it traverses the string in backward direction.
    rindex(str,beg=0,end=len(str))It is same as index but it traverses the string in backward direction.
    rjust(width,[,fillchar])Returns a space padded string having original string right justified to the number of characters specified.
    rstrip()It removes all trailing whitespace of a string and can also be used to remove particular character from trailing.
    rsplit(sep=None, maxsplit = -1)It is same as split() but it processes the string from the backward direction. It returns the list of words in the string. If Separator is not specified then the string splits according to the white-space.
    split(str,num=string.count(str))Splits the string according to the delimiter str. The string splits according to the space if the delimiter is not provided. It returns the list of substring concatenated with the delimiter.
    splitlines(num=string.count(‘\n’))It returns the list of strings at each line with newline removed.
    startswith(str,beg=0,end=len(str))It returns a Boolean value if the string starts with given str between begin and end.
    strip([chars])It is used to perform lstrip() and rstrip() on the string.
    swapcase()It inverts case of all characters in a string.
    title()It is used to convert the string into the title-case i.e., The string meEruT will be converted to Meerut.
    translate(table,deletechars = ”)It translates the string according to the translation table passed in the function .
    upper()It converts all the characters of a string to Upper Case.
    zfill(width)Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).
    rpartition()
  • Python Pass Statement

    What is Python’s Pass Statement?

    The pass statement is also known as the null statement. The Python mediator doesn’t overlook a Remark, though a pass proclamation isn’t. As a result, these two Python keywords are distinct.

    We can use the pass statement as a placeholder when unsure of the code to provide. Therefore, the pass only needs to be placed on that line. The pass might be utilized when we wish no code to be executed. We can simply insert a pass in cases where empty code is prohibited, such as in loops, functions, class definitions, and if-else statements.

    Syntax

    Keyword:  
    
        pass

    Ordinarily, we use it as a perspective for what’s to come.

    Let’s say we have an if-else statement or loop that we want to fill in the future but cannot. An empty body for the pass keyword would be grammatically incorrect. A mistake would be shown by the Python translator proposing to occupy the space. As a result, we use the pass statement to create a code block that does nothing.

    An Illustration of the Pass Statement

    Code

    # Python program to show how to use a pass statement in a for loop  
    
    '''''pass acts as a placeholder. We can fill this place later on'''  
    
    sequence = {"Python", "Pass", "Statement", "Placeholder"}  
    
    for value in sequence:  
    
        if value == "Pass":  
    
            pass # leaving an empty if block using the pass keyword  
    
        else:  
    
            print("Not reached pass keyword: ", value)

    Output:Not reached pass keyword: Python Not reached pass keyword: Placeholder Not reached pass keyword: Statement

    The same thing is also possible to create an empty function or a class.

    Code

    # Python program to show how to create an empty function and an empty class  
    
      
    
    # Empty function:  
    
    def empty():  
    
        pass  
    
      
    
    # Empty class  
    
    class Empty:  
    
        pass
  • Python continue Statement

    Python continue keyword is used to skip the remaining statements of the current loop and go to the next iteration. In Python, loops repeat processes on their own in an efficient way. However, there might be occasions when we wish to leave the current loop entirely, skip iteration, or dismiss the condition controlling the loop.

    We use Loop control statements in such cases. The continue keyword is a loop control statement that allows us to change the loop’s control. Both Python while and Python for loops can leverage the continue statements.

    Syntax:

    1. continue  

    Python Continue Statements in for Loop

    Printing numbers from 10 to 20 except 15 can be done using continue statement and for loop. The following code is an example of the above scenario:

    # Python code to show example of continue statement  
    
       
    
    # looping from 10 to 20  
    
    for iterator in range(10, 21):  
    
       
    
        # If iterator is equals to 15, loop will continue to the next iteration  
    
        if iterator == 15:  
    
            continue  
    
        # otherwise printing the value of iterator  
    
        print( iterator )

    Output:10 11 12 13 14 16 17 18 19 20

    Explanation: We will execute a loop from 10 to 20 and test the condition that the iterator is equal to 15. If it equals 15, we’ll employ the continue statement to skip to the following iteration displaying any output; otherwise, the loop will print the result.

    Python Continue Statements in while Loop

    Code

    # Creating a string  
    
    string = "JavaTpoint"  
    
    # initializing an iterator  
    
    iterator = 0  
    
       
    
    # starting a while loop                   
    
    while iterator < len(string):  
    
        # if loop is at letter a it will skip the remaining code and go to next iteration  
    
        if string[iterator] == 'a':    
    
            continue    
    
        # otherwise it will print the letter  
    
        print(string[ iterator ])  
    
        iterator += 1

    Output:J v T p o i n t

    Explanation: We will take a string “Javatpoint” and print each letter of the string except “a”. This time we will use Python while loop to do so. Until the value of the iterator is less than the string’s length, the while loop will keep executing.

    Python Continue statement in list comprehension

    Let’s see the example for continue statement in list comprehension.

    Code

    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  
    
      
    
    # Using a list comprehension with continue  
    
    sq_num = [num ** 2 for num in numbers if num % 2 == 0]  
    
    # This will skip odd numbers and only square the even numbers  
    
    print(sq_num)

    Output:[4, 16, 36, 64, 100]

    Explanation: In the above code, list comprehension will square the numbers from the list. And continue statement will be encountered when odd numbers come and the loop will skip the execution and moves to the next iterartion.

    Python Continue vs. Pass

    Usually, there is some confusion in the pass and continue keywords. So here are the differences between these two.

    Headingscontinuepass
    DefinitionThe continue statement is utilized to skip the current loop’s remaining statements, go to the following iteration, and return control to the beginning.The pass keyword is used when a phrase is necessary syntactically to be placed but not to be executed.
    ActionIt takes the control back to the start of the loop.Nothing happens if the Python interpreter encounters the pass statement.
    ApplicationIt works with both the Python while and Python for loops.It performs nothing; hence it is a null operation.
    SyntaxIt has the following syntax: -: continueIts syntax is as follows:- pass
    InterpretationIt’s mostly utilized within a loop’s condition.During the byte-compile stage, the pass keyword is removed.