Blog

  • Python OS Module

    Python OS module provides the facility to establish the interaction between the user and the operating system. It offers many useful OS functions that are used to perform OS-based tasks and get related information about the operating system.

    The OS module comes under Python’s standard utility modules. This module offers a portable way of using operating system-dependent functionality. It lets us work with the files and directories.

    To work with the OS module, we need to import the OS module.

    import os

    There are some functions in the OS module, which are given below:

    1. os.name()

    This function provides the name of the operating system module that it imports. Currently, it registers ‘posix’, ‘nt’, ‘os2’, ‘ce’, ‘java’, and ‘riscos’.

    Python os.name() Module Example

    Let us take an example to demonstrate the os.name() module in Python.

    import os   
    
    print(os.name)

    Output:

    nt
    

    2. os.mkdir()

    The os.mkdir() function is used to create a new directory.

    Python os.mkdir() Module Example

    Let us take an example to demonstrate the os.mkdir() module in Python.

    import os  
    
    os.mkdir("d:\\newdir")

    It will create a new directory in the path in the string argument of the function in the D drive named folder newdir.

    3. os.getcwd()

    It returns the current working directory (CWD) of the file.

    Python os.getcwd() Module Example

    Let us take an example to demonstrate the os.getcwd() module in Python.

    import os     
    
    print(os.getcwd())

    Output:

    C:\Users\Python\Desktop\ModuleOS
    

    4. os.chdir()

    The os module provides the chdir() function to change the current working directory.

    Python os.chdir() module Example

    Let’s consider an example to demonstrate the os.chdir() module in Python.

    import os  
    
    os.chdir("d:\\")

    Output:

    d:\\
    

    5. os.rmdir()

    The rmdir() function removes the specified directory with an absolute or relative path. First, we have to change the current working directory and remove the folder.

    Python os.rmdir() Module Example

    Let us take an example to demonstrate the os.rmdir() module in Python.

    import os  
    
    # It will throw a Permission error; that's why we have to change the current working directory.  
    
    os.rmdir("d:\\newdir")  
    
    os.chdir("..")  
    
    os.rmdir("newdir")

    6. os.error()

    The os.error() function defines the OS level errors. It raises OSError in case of invalid or inaccessible file names and paths, etc.

    Python os.error() module Example

    Let us take an example to demonstrate the os.error() module in Python.

    import os  
    
      
    
    try:  
    
        # If file does not exist,  
    
        # then it throw an IOError  
    
        filename = 'Python.txt'  
    
        f = open(filename, 'rU')  
    
        text = f.read()  
    
        f.close()  
    
      
    
    # The Control jumps directly to here if  
    
    # any lines throws IOError.  
    
    except IOError:  
    
      
    
        # print(os.error) will <class 'OSError'>  
    
        print('Problem reading: ' + filename)

    Output:

    Problem reading: Python.txt
    

    7. os.popen()

    This function opens a file or one specified by the command specified, and it returns a file object that is connected to a pipe.

    Python os.popen() Module Example

    Let us take an example to demonstrate the os.popen() module in Python.

    import os     
    
    fd = "python.txt"      
    
        
    
    # popen() is similar to open()     
    
    file = open(fd, 'w')     
    
    file.write("This is awesome")     
    
    file.close()     
    
    file = open(fd, 'r')     
    
    text = file.read()     
    
    print(text)     
    
          
    
    # popen() provides gateway and accesses the file directly     
    
    file = os.popen(fd, 'w')     
    
    file.write("This is awesome")     
    
    # File not closed, shown in next function.

    Output:

    This is awesome
    

    8. os.close()

    This function closes the associated file with descriptor fr.

    Python os.close() Module Example

    Let us take an example to demonstrate the os.close() module in Python.

    import os     
    
    fr = "Python1.txt"    
    
    file = open(fr, 'r')     
    
    text = file.read()     
    
    print(text)     
    
    os.close(file)

    Output:

    Traceback (most recent call last):
    File "main.py", line 3, in
    file = open(fr, 'r')
    FileNotFoundError: [Errno 2] No such file or directory: 'Python1.txt'
    

    9. os.rename()

    A file or directory can be renamed by using the function os.rename(). A user can rename the file if it has the privilege to change the file.

    Python os.rename() Module Example

    Let us take an example to demonstrate the os.rename() module in Python.

    import os     
    
    fd = "python.txt"    
    
    os.rename(fd,'Python1.txt')     
    
    os.rename(fd,'Python1.txt')

    Output:

    Traceback (most recent call last):
    File "main.py", line 3, in
    os.rename(fd,'Python1.txt')
    FileNotFoundError: [Errno 2] No such file or directory: 'python.txt' -> 'Python1.txt'
    

    10. os.access()

    This function uses real uid/gid to test if the invoking user has access to the path.

    Python os.access() Module Example

    Let us take an example to demonstrate the os.access() module in Python.

    import os     
    
    import sys    
    
        
    
    path1 = os.access("Python.txt", os.F_OK)     
    
    print("Exist path:", path1)     
    
          
    
    # Checking access with os.R_OK     
    
    path2 = os.access("Python.txt", os.R_OK)     
    
    print("It access to read the file:", path2)     
    
          
    
    # Checking access with os.W_OK     
    
    path3 = os.access("Python.txt", os.W_OK)     
    
    print("It access to write the file:", path3)     
    
          
    
    # Checking access with os.X_OK     
    
    path4 = os.access("Python.txt", os.X_OK)     
    
    print("Check if path can be executed:", path4)

    Output:

    Exist path: False
    It access to read the file: False
    It access to write the file: False
    Check if path can be executed: False
    

    Conclusion

    In this tutorial, we learnt about the OS module in Python. The Python OS module provides the facility to establish the interaction between the user and the operating system. We can import the OS module by import os. We studied various types of functions in the OS module, such as os.name(), os.mkdir(), os.getcwd(), os.close, etc, with their examples to understand the topic deeply.

  • Python math Module

    In Python, the math module is a built-in module that allows us to use mathematical tools and helps us to perform complex mathematical calculations, logarithms, exponentials, and other arithmetic operations.

    To read more Python Modules

    Python math Module

    Let’s see a simple example to understand the use of the Math module:

    Example: Finding Square Root

    Example

    #Importing the math module  
    
    import math  
    
    #Entering the number  
    
    num = int(input("Enter a number:"))  
    
    #We are sqrt() function to find the square root of the number  
    
    print(math.sqrt(num))  # Uses math module

    Output:

    Enter a number:25
    The square root of the number is: 5.0
    

    Explanation

    In the above example, we have imported the math module because it has built-in function sqrt() to find the square root.

    Constants in math Module

    The math module provides the values of several constants that we regularly use in mathematical contexts.

    For example, to find the area of a circle, we have to use pi because the formula is pi*r2, where r is the radius of the circle.

    So, the math module makes it easier for us by providing built-in constant values.

    Constant ValuesDefinition
    Pi(π)The value of pi(π) is 22/7 or 3.14 mathematically, we use math.pi to get the most accurate value.
    Euler’s number(e)The mathematically accepted value of Euler’s number, which is returned by math.e is 2.718281828459045.
    Tau(τ)The value of Tau, which is returned by math.tau is 6.283185307179586.
    Infinity(∞)The Mathematical value of Infinity, which is returned by math.inf, is inf. The infinity can be both Positive and Negative.
    Not a Number(NaN)The value of Not a Number(NaN), which is returned by math.nan, is nan, which is not a valid number.

    Example: Printing Constant Values

    Example

    #importing math module  
    
    import math  
    
    #Printing constant values  
    
    print("Value of Pi Constant=", math.pi)      #Pi's constant  
    
    print("Value of Euler's Constant=", math.e)   #Euler's constant  
    
    print("Value of Tau's Constant=", math.tau)   #Tau's constant  
    
    print("Value of Infinity =", math.inf)        #Infinity  
    
    print("Value of Not a Number =", math.nan)    #Not a Number

    Output:

    Value of Pi Constant 3.141592653589793
    Value of Euler's Constant 2.718281828459045
    Value of Tau's Constant 6.283185307179586
    Value of Infinity = inf
    Value of Not a Number = nan
    

    Explanation

    In the above example, we have imported the math module and printed the values of various mathematical constants using math.constant_name.

    Python math Module Functions

    As we know, the Python math module allows us to perform advanced mathematical calculations, such as trigonometric functions, logarithms, and exponentials. For performing the complex calculation math module provides the following built-in functions.

    S. N.FunctionsDescription
    1math.sin(x)It provides the sin value of x
    2math.cos(x)It gives the cosine value of x.
    3math.tan(x)It produces the tangent value of x.
    4math.asin(x)It provides the arc sine value of x.
    5math.acos(x)This function gives arc cosine value of x.
    6math.atan(x)This function gives the arc tangent value of x (in radians).
    7math.atan2(y, x)It provides the arc tangent value of y/x in radians.
    8math.sinh(x)Hyperbolic sin value.
    9math.cosh(x)Hyperbolic cosine value.
    10math.tanh(x)Hyperbolic tangent value.
    11math.asinh(x)Inverse hyperbolic sine value.
    12math.acosh(x)Inverse hyperbolic cosine value.
    13math.atanh(x)Inverse hyperbolic tangent value.
    14math.degrees(x)It converts radians to degrees.
    15math.radians(x)It converts degrees to radians.
    16math.exp(x)It gives ex.
    17math.expm1(x)It gives ex-1.
    18math.log(x, base)It gives the value of log with its base.
    19math.log10(x)It gives the Base 10 logarithm.
    20math.log1p(x)log(1+x).
    21math.log2(x)It gives the Base 2 logarithm.
    22math.pow(x, y)It gives xy.
    23math.sqrt(x)This generates the square root of the number.
    24math.fabs(x)It gives the absolute value.
    25math.factorial(n)It gives the factorial of number n.
    26math.comb(x, y)It produces the combinations.
    27math.perm(x, y)It produces the permutations.
    28math.isfinite(n)It checks if n is finite.
    29math.isinf(n)It checks if n is infinite.
    30math.gamma(x)It returns the gamma function of the argument.
    31math.lgamma(x)It returns the natural log of the gamma function.

    Example 1: Finding the Factorial of a Number

    In this example, we will see how to calculate the factorial of a number using the math module.

    Example

    #importing the math module  
    
    import math  
    
    n = int(input("Enter a number: "))  
    
    #using math.factorial() function  
    
    print("The factorial of the entered number is: ",math.factorial(n))

    Output:

    Enter a number: 5
    The factorial of the entered number is: 120
    

    Explanation

    In this example, we calculated the factorial of a number using math.factorial(n) function where n is the number entered by the user.

    Performing Trigonometric Operations

    The following example demonstrates how to calculate trigonometric ratios using the math module.

    Example: Using Trigonometric Operations

    Example

    #importing the math module  
    
    import math   
    
    #taking input from the user  
    
    n = int(input("Enter a number: "))  
    
    #returning the values of various trigonometric functions  
    
    print("The Sine value is: ",math.sin(n))  
    
    print("The Cosine value is: ",math.cos(n))  
    
    print("The Tan value is: ",math.tan(n))

    Output:

    Enter a number: 90
    The Sine value is: 0.8939966636005579
    The Cosine value is: -0.4480736161291701
    The Tan value is: -1.995200412208242
    

    Explanation

    In the above example, we have calculated the values of some trigonometric functions using the sin, cos and tan functions in the math module.

    Permutation and Combination

    In the following example, we will determine the number of ways to choose a given number of balls from a bag of balls. In order to find the combination, we will be using the math.comb() function.

    Example: Ways of Choosing Balls from a Bag

    Example

    #importing the math module  
    
    import math  
    
    # given data  
    
    n = 10  # total no of balls  
    
    r = 4       # number of balls to be selected  
    
    # Finding the number of combinations using math.comb()  
    
    no_of_ways = math.comb(n, r)  
    
    # printing result  
    
    print("Given Data:")  
    
    print("Total number of Balls in the bag:", n)  
    
    print("Number of Balls to be selected:", r)  
    
    print("Total number of Ways to select", r, "balls from the bag of", n, "balls:")  
    
    print(no_of_ways)

    Output:

    Given Data:
    Total number of Balls in the bag: 10
    Number of Balls to be selected: 4
    Total number of Ways to select 4 balls from the bag of 10 balls:
    210
    

    Explanation

    Here we calculated the number of ways to choose 4 balls from the bag of 10 balls using math.comb() function

    Example 4: Degree to Radians and Vice-Versa  Conversion

    Here, we will convert radians to degrees and degrees to Radians by taking input from the user.

    Example

    #importing the math module  
    
    import math  
    
    # Taking input in radians and converting to degrees  
    
    rad = float(input("Enter the angle in radians: "))  
    
    print("Radians to Degrees =", math.degrees(rad))  
    
    # Taking input in degrees and converting to radians  
    
    deg = float(input("Enter the angle in degrees: "))  
    
    print("Degrees to Radians =", math.radians(deg))

    Output:

    Enter the angle in radians: 6.28318530718
    Radians to Degrees = 360.0000000000237
    Enter the angle in degrees: 360
    Degrees to Radians = 6.283185307179586
    

    Explanation

    In this example, we have used math.degrees() and math.radians() functions to convert radians to degrees and vice versa, receiving input from the user.

    Calculating Exponential

    x to the power of e, often known as the exponential of a number x, is calculated using the exp() function.

    Example

    # Python program to show how to use the exp() function.    
    
    # importing the math module    
    
    import math    
    
    # declaring some value    
    
    num1 = 4    
    
    num2 = -3    
    
    num3 = 0.00    
    
    # passing above values to the exp() function    
    
    print( f"The exponenetial value of {num1} is: ", math.exp(num1) )    
    
    print( f"The exponenetial value of {num2} is: ", math.exp(num2) )    
    
    print( f"The exponenetial value of {num3} is: ", math.exp(num3) )

    Output:

    The exponenetial value of 4 is: 54.598150033144236
    The exponenetial value of -3 is: 0.049787068367863944
    The exponenetial value of 0.0 is: 1.0
    

    Using dir() Function

    A sorted list of strings comprising the identifiers of the functions defined by a module is what the built-in method dir() delivers.

    The list includes the names of modules, each specified constants, functions, and methods. Here is a straightforward illustration:

    Example

    # Importing the math module    
    
    import math    
    
    functions = dir(math)    
    
    print( functions )

    Output:

    ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']

    Conclusion

    The Python Math Module is a built-in module that allows us to perform advanced mathematical calculations, such as trigonometric functions, logarithms, and exponentials. We got to know about various types of functions, such as exponential and logarithmic functions. We learned about Constant values and their applications.

  • Python Collection Module

    The Collections Module in Python is different than the other built-in modules. This module contains some different types of containers which is used to store different types of objects.

    The Python collection module is defined as a container that is used to store collections of data, for example – list, dict, set, and tuple, etc. It was introduced to improve the functionalities of the built-in collection containers. Python collection module was first introduced in its 2.4 release.

    Some common and widely used collection modules are as follows:

    • Counters
    • Default Dictionary
    • ChainMap
    • NamedTuple
    • Deque
    • UserDict
    • UserList
    • UserString

    Counters

    The Counters is a part of the Dictionary and is used to count of number of elements in pairs. The dictionary is an unordered, mutable, and indexed collection where each key is unique and maps to the associated value, but since Python 3.7, the insertion in the dictionary is ordered.

    We have to import the ordereddict module by using the following command:

    from collections import OrderedDict

    Python Counter Syntax

    It has the following syntax:

    class collections.OrderDict()  

    Python Counter Example

    Let us take an example to demonstrate the Counter collection module in Python.

    Example

    #importing the counter from the collections  
    
    from collections import OrderedDict  
    
    print("This is a Dictionary:\n")  
    
    d = {}  
    
    d['w'] = 11  
    
    d['x'] = 12  
    
    d['y'] = 13  
    
    d['z'] = 14  
    
    for key, value in d.items():    
    
        print(key, value)  
    
    print("\nThis is an Ordered Dict:\n")  
    
    od = OrderedDict()  
    
    od['a'] = 1  
    
    od['b'] = 2  
    
    od['c'] = 3  
    
    od['d'] = 4  
    
    for key, value in od.items():  
    
        print(key, value)

    Output:

    This is a Dictionary:
    
    w 11
    x 12
    y 13
    z 14
    
    This is an Ordered Dict:
    
    a 1
    b 2
    c 3
    d 4
    

    Example of deleting and reinserting a key

    Let us take an example to demponstrate how to delete and reinsert a key using Python collection module.

    Example

    #importing the counter from the collections  
    
    from collections import OrderedDict  
    
    odict = OrderedDict()  
    
    odict['w'] = 100  
    
    odict['x'] = 200  
    
    odict['y'] = 300  
    
    odict['z'] = 400  
    
    print('Before Deleting')  
    
    for key, value in odict.items():  
    
        print(key, value)  
    
    # deleting the element  
    
    odict.pop('w')  
    
    # Re-inserting the same element  
    
    odict['w'] = 100  
    
    print('\nAfter re-inserting')  
    
    for key, value in odict.items():  
    
        print(key, value)

    Output:

    Before Deleting
    w 100
    x 200
    y 300
    z 400
    
    After re-inserting
    x 200
    y 300
    z 400
    w 100
    

    DefaultDict

    The DefaultDict consists of default values assigned to a key that does not exist, and because of this, it does not raise any error.

    Python DefaultDictSyntax

    It has the following syntax:

    class collections.defaultdict(default_factory)  

    We can initialize the default dictionary by using the DefaultDict() function by passing data types as arguments.

    Python DefaultDict Example

    Let us take an example to demonstrate the DefaultDict collection module in Python.

    Example

    #importing the counter from the collections  
    
    from collections import defaultdict  
    
    # here we are creating a default dictionary with the default value of 0 (int)  
    
    dict = defaultdict(int)  
    
    A = [1,4,2,3,1,2,5,6,2]  
    
    # Counting occurrences of each element in the list  
    
    for i in A:  
    
        dict[i] += 1  
    
    print(dict)

    Output:

    defaultdict(<class 'int'>, {1: 2, 4: 1, 2: 3, 3: 1, 5: 1, 6: 1})

    ChainMap

    The ChainMap collects and accumulates multiple dictionaries into a single unit and then generates a list of dictionaries.

    We can import the ChainMap by the following code:

    from collections import ChainMap  

    Python ChainMap Syntax

    It has the following syntax:

    class collections.ChainMap(dict1, dict2)  

    Python ChainMap Example

    Let us take an example to illustrate the ChainMap collection module in Python.

    Example

    #importing the counter from the collections  
    
    from collections import ChainMap  
    
    dict1 = {'a': 100, 'b': 200}  
    
    dict2 = {'c': 300, 'd': 400}  
    
    dict3 = {'e': 500, 'f': 600}  
    
    #merging the multiple dictionaries  
    
    c = ChainMap(dict1, dict2, dict3)  
    
    # printing the output  
    
    print(c)

    Output:

    ChainMap({'a': 100, 'b': 200}, {'c': 300, 'd': 400}, {'e': 500, 'f': 600})

    We can also use the key name to access the value from ChainMap.keys() and values() methods can also be used to access.

    Example

    # Importing namedtuple from the collections module  
    
    from collections import ChainMap  
    
    dict1 = {'a': 100, 'b': 200}  
    
    dict2 = {'c': 300, 'd': 400}  
    
    dict3 = {'e': 500, 'f': 600}  
    
    # here we are creating the chainmap  
    
    cm = ChainMap(dict1, dict2 , dict3)  
    
    # Accessing Values using key name  
    
    print(cm['a'])  
    
    # Accessing values using values() method  
    
    print(cm.values())  
    
    # Accessing keys using keys() method  
    
    print(cm.keys())

    Output:

    100
    ValuesView(ChainMap({'a': 100, 'b': 200}, {'c': 300, 'd': 400}, {'e': 500, 'f': 600}))
    KeysView(ChainMap({'a': 100, 'b': 200}, {'c': 300, 'd': 400}, {'e': 500, 'f': 600}))
    

    Adding a new dictionary

    We can use the new_child() method to add a new dictionary at the beginning of the ChainMap.

    Example

    #importing the collections module  
    
    import collections  
    
    # creating the dictionaries  
    
    dict1 = { 'a' : 123, 'b' : 456 }  
    
    dict2 = { 'b' : 789, 'c' : 111 }  
    
    dict3 = { 'f' : 1213 }  
    
    # initializing ChainMap  
    
    chain = collections.ChainMap(dict1, dict2)  
    
    # printing chainMap  
    
    print ("The contents of the ChainMap are: ")  
    
    print (chain)  
    
    # here we are using the  new_child() to add new dictionary  
    
    n_chain = chain.new_child(dict3)  
    
    # printing chainMap  
    
    print ("Showing new ChainMap : ")  
    
    print (n_chain)

    Output:

    The contents of the ChainMap are:
    ChainMap({'a': 123, 'b': 456}, {'b': 789, 'c': 111})
    Showing new ChainMap :
    ChainMap({'f': 1213}, {'a': 123, 'b': 456}, {'b': 789, 'c': 111})
    

    NamedTuple

    A tuple is an ordered, immutable collection of elements, which means that once created, its elements cannot be changed. A NamedTuple is similar to a tuple, the only difference being that it consists of named fields, which makes the data easier to read, interpret, and access.

    We can import the NamedTuple with the following code:

    from collections import namedtuple

    Python NamedTuple Syntax

    It has the following syntax:

    class collections.namedtuple(typename, field_names)  

    Python NamedTuple Example

    Let us take an example to demonstrate the NamedTuple collection module in Python.

    Example

    # Importing namedtuple from the collections module  
    
    from collections import namedtuple  
    
    # Creating namedtuple()  
    
    Employee = namedtuple('Employee', ['name', 'age', 'ID_number'])  
    
    # Creating an instance of an Employee  
    
    E = Employee('Abhay', '23', '280202')  
    
    # Access using index  
    
    print("The Employee age using index is: ", end="")  
    
    print(E[1])  
    
    # Access using field name    
    
    print("The Employee ID number using field name is: ", end="")  
    
    print(E.ID_number)  
    
    print("The Employee name is: ", end="")  
    
    print(E.name)

    Output:

    The Employee age using index is: 23
    The Employee ID number using field name is: 280202
    The Employee name is: Abhay
    

    Deque

    Deque stands for Doubly Ended Queue. It is a data structure in the collections which is used to perform append and pop operations on both ends of the data structure.

    Deque word is often pronounced as the word “Deck”. The time complexity for the pop and append operations is O(1), whereas for the list it is O(n).

    Python Deque Syntax:

    The Syntax for the deque data structure is:

    class collections.deque(list)  

    Python Deque Example

    Let us take an example to demonstrate the deque collection module in Python.

    Example

    #importing the deque data structure from collection  
    
    from collections import deque  
    
    # Declaring deque  
    
    q1 = deque(['name','company','empid'])  
    
    print(q1)

    Output:

    deque(['name', 'company', 'empid'])

    Inserting Elements

    Using the deque data structure, we add and insert the elements in the deque from both ends. We use the append() method to insert the element from the right and the appendleft() method to insert from the left.

    Python Example for Inserting Elements

    Let us take an example to demonstrate how to insert element in a deque using append() function.

    Example

    #importing the deque data structure from collection  
    
    from collections import deque  
    
    # Initializing deque with initial values  
    
    de = deque([123, 456, 789])  
    
    # here we appending a number 2025 to the right end of deque  
    
    de.append(2025)  
    
    #printing the deque after the number to the right end  
    
    print("The deque after appending at right is :")  
    
    print(de)  
    
    #now we are appending the number to the left end of the deque  
    
    de.appendleft(100)  
    
    #printing the deque after the number to the left  
    
    print("The deque after appending at left is :")  
    
    print(de)

    Output:

    The deque after appending at right is :
    deque([123, 456, 789, 2025])
    The deque after appending at left is :
    deque([100, 123, 456, 789, 2025])
    

    Removing Elements

    We added the elements on the left and right sides using the append() method. Similarly, we can also remove the elements from the deque using the pop() method. We use the pop() method to remove the element from the deque from the right end and popleft() to remove from the left end.

    Python Example to Remove Elements using Deque

    Let us take an example to demonstrate how to remove elements from a deque using the pop function in Python.

    Example

    #importing the deque data structure from collection  
    
    from collections import deque  
    
    # Initialize deque with initial values  
    
    de = deque([2016, 2017, 2018, 2019, 2020])  
    
    # here we deleting a number from the right end of deque  
    
    de.pop()  
    
    #printing the deque after deleting the number from the right end  
    
    print("The deque after deleting from right is :")  
    
    print(de)  
    
    #now we are deleting the number from the left end of the deque  
    
    de.popleft()  
    
    #printing the deque after deleting the number from the left  
    
    print("The deque after deleting from left is :")  
    
    print(de)

    Output:

    The deque after deleting from right is :
    deque([2016, 2017, 2018, 2019])
    The deque after deleting from left is :
    deque([2017, 2018, 2019])
    

    UserDict

    UserDict behaves as a container that is wrapped around the dictionary objects. It is used for creating a dictionary with extra features, functions, etc.

    Python UserDict Syntax:

    It has the following syntax:

    class collections.UserDict([initialdata])  

    Python UserDict Example

    Let us take an example to demonstrate the UserDict collection module in Python.

    Example

    #importing the UserDict from collection  
    
    from collections import UserDict  
    
    # we are creating a dictionary where deletion is prohibited  
    
    class Dict(UserDict):  
    
        # It stops using 'del' on dictionary  
    
        def __del__(self):  
    
            raise RuntimeError("Deletion not allowed")  
    
        # It prevents using pop() on dictionary  
    
        def pop(self, s=None):  
    
            raise RuntimeError("Deletion not allowed")  
    
        # It prevents using popitem() on dictionary  
    
        def popitem(self, s=None):  
    
            raise RuntimeError("Deletion not allowed")  
    
    # Create an instance of MyDict  
    
    d = Dict({'a': 100, 'b': 200, 'c': 300})  
    
    d.pop(1)

    Output:

    ---------------------------------------------------------------------------
    RuntimeError Traceback (most recent call last)
    Cell In[13], line 21
    19 # Create an instance of MyDict
    20 d = Dict({'a': 1, 'b': 2, 'c': 3})
    ---> 21 d.pop(1)
    Cell In[13], line 13
    12 def pop(self, s=None):
    ---> 13 raise RuntimeError("Deletion not allowed")
    RuntimeError: Deletion not allowed
    

    UserList

    We studied that UserDict behaves a wrapper for dictionary objects, similarly, the UserList acts as a container that is wrapped around the list objects. It is used for creating a string with extra features, functions, etc.

    Python UserList Syntax:

    It has the following syntax:

    class collections.UserList([list])  

    Python UserList Example

    Let us take an example to demonstrate the UserList collection module in Python.

    Example

    #importing the UserList from collection  
    
    from collections import UserList  
    
    # we are creating a list and deletion of the object is prohibited  
    
    class List(UserList):  
    
        # Prevents using remove() on list  
    
        def remove(self, s=None):  
    
            raise RuntimeError("Deletion not allowed")  
    
        # Prevents using pop() on list  
    
        def pop(self, s=None):  
    
            raise RuntimeError("Deletion not allowed")  
    
    #  We are Creating an instance of List  
    
    L = List([100, 200, 300, 400])  
    
    print("Original List")  
    
    #here we are Appending 500 to the list  
    
    L.append(500)  
    
    print("After Insertion")  
    
    print(L)  
    
    # Attempt to remove an item (will raise error)  
    
    L.remove()

    Output:

    Original List
    After Insertion
    [100, 200, 300, 400, 500]
    ---------------------------------------------------------------------------
    RuntimeError Traceback (most recent call last)
    Cell In[6], line 24
    22 print(L)
    23 # Attempt to remove an item (will raise error)
    ---> 24 L.remove()
    
    Cell In[6], line 9
    8 def remove(self, s=None):
    ----> 9 raise RuntimeError("Deletion not allowed")
    
    RuntimeError: Deletion not allowed
    

    UserString

    Just UserList behaves as a container that is wrapped around the list objects. The UserString acts as a container that is wrapped around the string objects. It is used for creating a string with extra features, functions, etc.

    Python UserString Syntax

    It has the following syntax:

    class collections.UserString(sequence)  

    Python UserString Example

    Let us take an example to demonstrate the UserString collection module in Python.

    Example

    # importing the UserString from collection  
    from collections import UserString  
    
    # Creating a Mutable String  
    class string(UserString):  
        # defining a function to append to string  
        def append(self, s):  
            self.data += s  
        
        # defining a function to remove from string  
        def remove(self, s):  
            self.data = self.data.replace(s, "")  
    
    # inputting the string  
    str_obj = string("Learn Python App")  
    print("Original String:", str_obj.data)  
    
    # appending a character or word to the string  
    str_obj.append("!")  
    print("String After Appending:", str_obj.data)  
    
    # deleting a specific letter from the string  
    # (In this case, removing 'p' from 'App')
    str_obj.remove("p")  
    print("String after Removing:", str_obj.data)

    Output:

    Original String: Learn Python App
    String After Appending: Learn Python App!
    String after Removing: Learn Python A!

    Conclusion

    In this tutorial, we learnt about Python Collections. The Collections Module in Python is different than the other built-in modules. This module contains some different types of containers which is used to store different types of objects. We learnt about various collection modules like Counters, Default Dictionary, ChainMap, NamedTuple, Deque, UserDict, UserList, and UserString

  • Python List Comprehension

    In Python, List Comprehension provides a concise and efficient way to create a new list. The new lists can be created with conditions and filters, which will be applied to the existing list.

    Python List Comprehension

    Syntax of Python List Comprehension

    The following is the syntax of the Python List Comprehension:

    new_list = [expression for item in iterable]  

    Parameters:

    • expression: The expression determines what gets added to the new list
    • item: Item taken from iterable
    • iterable: sequential data types, such as list, tuple, string, etc.

    Return Value:

    • This method returns a new list after applying the expression and conditions.

    Python List Comprehension Example

    Let us see a simple example showing how list comprehension works.

    Example

    numlist= [4,32,6,76,12,37,52]  
    
      
    
    square = [sol ** 2 for sol in numlist]  
    
      
    
    print(square)

    Output:

    [16, 1024, 36, 5776, 144, 1369, 2704]

    Explanation:

    In the above example, we created a list of numbers named sqrt_num. Then, using list comprehension, we created a new list named square that gives the square of every number in sqrt_num.

    Difference between For Loop and List Comprehension

    The primary difference between a for loop and list comprehension is that for loops often consist of multiple lines to iterate through elements and build a new list. On the other hand, list comprehension takes only one line of code to create a new list. Hence making it clean, readable and much more efficient.

    Let’s see an example to understand this clearly:

    1) Using For Loop

    In this example, we are using a for loop to find the square of the number in the list.

    Example

    numlist = [4, 32, 6, 76, 12, 37, 52]  
    
      
    
    square = []  # Create an empty list 'square' to store results  
    
      
    
    for sol in numlist:  # Iterate over each element in the list 'numlist'  
    
        square.append(sol ** 2)  # Square each element and append to 'square'  
    
      
    
    print(square)

    Output:

    [16, 1024, 36, 5776, 144, 1369, 2704]

    Explanation:

    In the above example, we created a list named numlist containing numbers, and an empty list named square to store the results. We used a for loop to iterate through each element in the numlist and squared each number using sol ** 2. After that, we appended the result to the square list.

    2) Using List Comprehension:

    In this example, we are using the List Comprehension method to create a new list:

    Example

    #created a list  
    
    numlist = [4, 32, 6, 76, 12, 37, 52]          
    
    #making a new list with condition  
    
    square = [sol ** 2 for sol in numlist]    
    
    print(square)

    Output:

    [16, 1024, 36, 5776, 144, 1369, 2704]

    Explanation:

    In the above example, we used List comprehension to create a new list named ‘square’ by squaring each element from the original list named ‘numlist’.

    As we can clearly see, the difference between a ‘for’ loop and list comprehension is evident. The ‘for’ loop requires three lines of code, whereas the list comprehension requires only one line of code.

    Conditional Statements in List Comprehension

    Conditional Statements in List Comprehension allow the use of if-else to determine or extract items based on specific conditions.

    Different Examples for Conditional Statements in Python List Comprehension

    Let’s see some examples to understand the use of conditional statements in Python List Comprehension:

    Example 1:

    In this example, we will create a list of the elements from the given list if the element consists of the character ‘a’.

    Example

    # given list  
    
    car = ['tata', 'honda', 'toyota', 'hyundai', 'skoda', 'suzuki', 'mahindra', 'BMW', 'Mercedes']  
    
    # making a new list with condition  
    
    new_carlist = [x for x in car if 'a' in x]        
    
    # printing new list  
    
    print(new_carlist)

    Output:

    ['tata', 'honda', 'toyota', 'hyundai', 'skoda', 'mahindra']

    Explanation:

    In the above example, we are given a list named ‘car’. We used the list comprehension to create a new list called new_carlist with a condition that extracts only those car names that contain the character ‘a’.

    Example 2:

    In the following example, we will create a list of cars that do not include the Indian car brands.

    Example

    car = ['tata', 'honda', 'toyota', 'hyundai', 'skoda','suzuki', 'mahindra', 'BMW', 'Mercedes']  
    
    indian_cars = ['tata', 'mahindra']  
    
    new_carlist = [x for x in car if x not in indian_cars]  
    
    print(new_carlist)

    Output:

    ['honda', 'toyota', 'hyundai', 'skoda', 'suzuki', 'BMW', 'Mercedes']

    Explanation:

    Here, we used list comprehension to exclude the Indian cars from the car list. The condition ‘if x not in indian_cars’ filters out any car that is listed in ‘indian_cars’ and adds only the non-Indian cars to ‘new_carlist’.

    List Comprehension with String

    The List Comprehension also helps us to extract elements from a string.

    Python List Comprehension Example with String 

    Let us take an example to demonstrate the list comprehension with string in Python.

    Example

    name = "Learn python app"  
    vowels = "aeiou"  
    
    # find vowel in the string "Learn python app"  
    solution = [letter for letter in name if letter in vowels]  
    
    print(solution)

    Output:

    
    ['e', 'a', 'o', 'a']

    Explanation:

    In the above example, we used list comprehension to iterate through the string “TpointTech” and extract all the vowels. The ‘solution’ stores the result.

    Creating a List from range()

    When we use the range() function in list comprehension, it helps us to print a large list of numbers.

    Python List Comprehension Example using range() Function

    Let’s consider an example to demonstrate how to create a list using the range() function in Python.

    Example

    # Creating a list of numbers from 0 to 5  
    
    num = [x for x in range(5)]  
    
      
    
    print(num)

    Output:

    [0, 1, 2, 3, 4]

    Explanation:

    In this example, we have created a list containing numbers using list comprehension. Here, we can see that we have used the range() function to return a range object consisting of the value from 0 to 4.

    Creating a List using Nested Loops

    We can also create a list using nested loops in List Comprehension. Let us take a look at an example showing how to create a list using nested loop:

    Example

    #printing cubes of the given range  
    
    #List comprehension using nested loop  
    
    cubes = [(i, i**3) for i in range(1, 6)]  
    
    print(cubes)

    Output:

    [(1, 1), (2, 8), (3, 27), (4, 64), (5, 125)]

    Explanation:

    In the above example, we created a nested for loop, i in range(1,6) gives values from 1 to 5 and for each i, we calculate its cube using i**3. The List comprehension stores the output in pairs.

    Flattening a list of lists

    In Python, we can use list comprehension to flatten a nested list (or list of lists). Flattening a list means converting a nested list into a single list with all its elements.

    Python List Comprehension Example for Flattening a list of lists

    Let us take an example to demonstrate how to flatten a list of lists in Python list comprehension.

    Example

    #given list  
    
    lists = [[3, 56, 21], [59, 15, 36], [27, 88, 69]]  
    
    #using the list comprehension method  
    
    solution = [x for y in lists for x in y]      
    
    print(solution)

    Output:

    [3, 56, 21, 59, 15, 36, 27, 88, 69]

    Explanation:

    • for y in list: It iterates over each sublist [1,2,3] and then [4,5,6]
    • for x in y: It iterates over each element in that sublist.
    • x: adds each element into the flattened list

    Conclusion

    Python List Comprehension is an effective method for extracting items from a list and creating a new list based on specific conditions.

    List Comprehension can be used with:

    • String (character filtering or transformation)
    • Nested Loops (for matrix operations or combinations)
    • Flattening of List
    • range() method (to generate sequences)
    • Conditional Statements (to filter or modify data)

    List comprehension isn’t limited to these examples and applications; one must try to explore the depth of this topic.

  • Python Modules

    In Python, a module is referred to as a file comprising of functions, classes, or variables. It helps us organizing the code logically and reuse it across different programs. There are many Python modules, each with its specific work.

    What is a Module in Python?

    A Python module is a file consisting of Python script (generally, with a .py extension) having definitions of functions, classes, or variables. A module can also include runnable code.

    Putting related code into a module makes it easier to read, use again in other programs, and keep everything organized.

    There are three types of modules in Python:

    1. User-defined Modules
    2. Built-in Modules
    3. Third-Party Modules

    Creating a Python Module

    In order to create a Python module, we need to write the desire code and save that in a file with the .py extension.

    Python Example to Create a Module

    Let’s consider an example to demonstrate how to create a python module.

    Example

    # module: calculator.py  
    
      
    
    # function to add two numbers  
    
    def add(a, b):  
    
      return a + b  
    
      
    
    # function to subtract two numbers  
    
    def subtract(a, b):  
    
      return a - b  
    
      
    
    # function to multiply two numbers  
    
    def multiply(a, b):  
    
      return a * b  
    
      
    
    # function to divide two numbers  
    
    def divide(a, b):  
    
      return a / b

    Explanation:

    In the above example, we have created a Python script consisting of some functions that will help us add, subtract, multiply, and divide two numbers. We have saved this file as calculator.py. This user-defined module can be used in other Python programs.

    Importing Module in Python

    In Python, we can import the functions and classes defined in a module to another module or the interactive interpreter. This can be used the import statement as shown below:

    Importing Module Syntax in Python

    It has the following syntax:

    import module_name  

    Using the import keyword followed by the module_name allow us to use the functions defined in that module.

    Note: Using the import statement, we import the whole module. In order to access the function from the imported module, we need to use the dot . operator.

    Python Example for Importing Module

    Let us take a look at the following example where we will try to import the user-defined module ‘calculator.py’ and use its functions.

    Example

    # importing the module  
    
    import calculator  
    
      
    
    # initializing some variables  
    
    num_1 = 16  
    
    num_2 = 7  
    
      
    
    # calling the functions of the module  
    
    total = calculator.add(num_1, num_2)  
    
    diff = calculator.subtract(num_1, num_2)   
    
    prod = calculator.multiply(num_1, num_2)  
    
    quot = calculator.divide(num_1, num_2)  
    
      
    
    # printing results  
    
    print(num_1, '+', num_2, '=', total)  
    
    print(num_1, '-', num_2, '=', diff)  
    
    print(num_1, '*', num_2, '=', prod)  
    
    print(num_1, '/', num_2, '=', quot)

    Output:

    16 + 7 = 23
    16 - 7 = 9
    16 * 7 = 112
    16 / 7 = 2.2857142857142856
    

    Explanation:

    In this example, we have imported the user-defined module ‘calculator’ and created two variables. We have then accessed the different functions like add(), subtract(), multiply() and divide() of the ‘calculator’ module and store their results in some variables. At last, we printed the results.

    Python Import with Renaming

    In Python, we can import a module by renaming it. This process allows us to use an alias (a shorter reference) for that module.

    Python Import and Renaming Example

    Let us take a look at the following example for better understanding.

    Example

    # importing the module with alias  
    
    import calculator as cal  
    
      
    
    # initializing some variables  
    
    num_1 = 25  
    
    num_2 = 9  
    
      
    
    # calling the functions of the module  
    
    total = cal.add(num_1, num_2)  
    
    diff = cal.subtract(num_1, num_2)   
    
    prod = cal.multiply(num_1, num_2)  
    
    quot = cal.divide(num_1, num_2)  
    
      
    
    # printing results  
    
    print(num_1, '+', num_2, '=', total)  
    
    print(num_1, '-', num_2, '=', diff)  
    
    print(num_1, '*', num_2, '=', prod)  
    
    print(num_1, '/', num_2, '=', quot)

    Output:

    25 + 9 = 34
    25 - 9 = 16
    25 * 9 = 225
    25 / 9 = 2.7777777777777777
    

    Explanation:

    In the above example, we have imported the user-defined module ‘calculator’ as ‘cal’ and created two variables. We have then accessed the different functions like add(), subtract(), multiple(), and divide() of the imported module using cal followed by the function name. We stored the results of these functions in different variables and printed their values.

    Python from…import Statement

    Python allows us to import specific attributes without importing the module as a whole. To understand this, let us see the following example:

    Example

    # importing certain attributes from the module  
    
    from calculator import subtract, multiply  
    
      
    
    # initializing some variables  
    
    num_1 = 12  
    
    num_2 = 7  
    
      
    
    # calling the imported functions  
    
    diff = subtract(num_1, num_2)  
    
    prod = multiply(num_1, num_2)  
    
      
    
    # printing results  
    
    print(num_1, '-', num_2, '=', diff)  
    
    print(num_1, '*', num_2, '=', prod)

    Output:

    12 - 7 = 5
    12 * 7 = 84
    

    Explanation:

    In the above example, we have imported the subtract() and multiply() functions from the user-defined module ‘calculator’. We have then initialized two variables and called the imported functions to calculate the difference and product of the numbers. At last, we have printed the resultant values.

    Importing All Attributes

    Similar to importing a certain attributes from the module, we can use the asterisk * symbol to import everything from the module.

    Syntax:

    It has the following syntax:

    from module_name import *  

    Python Example for Importing All Attributes 

    Here is an example showing the same:

    Example

    # importing everything from the module  
    
    from calculator import *  
    
      
    
    # initializing some variables  
    
    num_1 = 19  
    
    num_2 = 14  
    
      
    
    # calling the imported functions  
    
    prod = multiply(num_1, num_2)  
    
    quot = divide(num_1, num_2)  
    
      
    
    # printing results  
    
    print(num_1, '*', num_2, '=', prod)  
    
    print(num_1, '/', num_2, '=', quot)

    Output:

    19 * 14 = 266
    19 / 14 = 1.3571428571428572
    

    Explanation:

    In this example, we have imported everything from the user-defined module ‘calculator’ using the asterisk * symbol. We have then initialized two variables and called the multiply() and divide() functions to calculate the product and division of the numbers. At last, we have printed the resultant values.

    Locating Python Modules

    Whenever we import a module into a program, the Python interpreter looks for numerous locations. First of all, it checks whether the imported module is a built-in module; if not, then it looks for a list of directories defined in the sys.path. Python interpreter searches for the module in the following way:

    Step 1: Firstly, it searches for the module in the current directory.

    Step 2: If the module is not found in the current directory, Python then searches each directory in the shell variable, PYTHONPATH. It is an environment variable that contains a list of directories.

    Step 3: In case, the module is not found, Python checks the installation-dependent list of directories configured at the time Python is installed.

    In order to check the list of directories, we can use the path variable from the sys module as shown below:

    Example

    # importing the sys module  
    
    import sys  
    
      
    
    # using the 'path' variable from the sys module  
    
    print(sys.path)

    Output:

    ['/content', '/env/python', '/usr/lib/python311.zip', '/usr/lib/python3.11', '/usr/lib/python3.11/lib-dynload', '', '/usr/local/lib/python3.11/dist-packages', '/usr/lib/python3/dist-packages', '/usr/local/lib/python3.11/dist-packages/IPython/extensions', '/usr/local/lib/python3.11/dist-packages/setuptools/_vendor', '/root/.ipython']

    Explanation:

    In the above example, we have imported the sys module and used its path variable to return the list of directories for the modules.

    Built-in dir() Function

    Python offers a built-in function called dir() that helps list all the attribute (function, class, variable) names in a module. For example, earlier, we defined a few functions like add(), subtract(), multiply(), and divide() in the ‘calculator’ module. We can use the dir() in order to fetch the details of these attributes in the following manner:

    Example

    # importing the user-defined module  
    
    import calculator  
    
      
    
    # listing all the attributes from the module  
    
    print(dir(calculator))

    Output:

    ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'add', 'divide', 'multiply', 'subtract']

    Explanation:

    In the above example, we have imported the user-defined module ‘calculator’ and called the dir() function to list all the attributes from the imported module.

    As a result, we can see a list of user-defined functions like add(), divide(), multiply(), and subtract() from the ‘calculator’ module. All other names that start with an underscore are default Python attributes related to the module (not user-defined). For example, the __name__ attribute stores the name of the module.

    Python Built-in Modules

    Python comes with several built-in modules that offer various amazing functions and features for different tasks. We can use the import statement to import these modules into the project whenever we like.

    Different Examples for Python Built-in Modules

    Let us look at some of the examples showing how to import and use the built-in modules in Python.

    Example 1: Importing the built-in math Module

    In this example, we will see how to import the math module and look at the usage of some of its attributes and functions.

    Example

    # importing the math module  
    
    import math  
    
      
    
    # using the variables and functions from the imported module  
    
    print("Pi =", math.pi)  # returns value of Pi  
    
    print("Square root of 16 =", math.sqrt(16))  # returns square root of 16  
    
    print("Floor value of 19.5 =", math.floor(19.5)) # returns floor value of 19.5  
    
    print("Ceiling value of 24.7 =", math.ceil(24.7))  # returns ceiling value of 24.7  
    
    print("Factorial of 6 =", math.factorial(6)) # returns factorial of 6

    Output:

    Pi = 3.141592653589793
    Square root of 16 = 4.0
    Floor value of 19.5 = 19
    Ceiling value of 24.7 = 25
    Factorial of 6 = 720
    

    Explanation:

    In the above example, we have imported the math module. We have used the different variables and functions of the math module.

    Example 2: Importing the built-in random Module

    Here, we will see how to import the random module and look at the usage of some of its functions.

    Example

    # importing the random module  
    
    import random  
    
      
    
    # given list  
    
    list_1 = [1, 4, True, 800, "python", 27, "hello"]  
    
      
    
    # using the functions from the imported modules  
    
    print("Random Integer between 10 and 50 =", random.randint(10, 50)) # returns a random integer between 10 and 50  
    
    print("Random Floating Point between 0 and 1 =", random.random())  # returns a floating point between 0 and 1  
    
    print("Random Item from the List =", random.choice(list_1)) # returns a random item from the list

    Output:

    Random Integer between 10 and 50 = 48
    Random Floating Point between 0 and 1 = 0.9739271518285192
    Random Item from the List = 4
    

    Explanation:

    In the above example, we have imported the random module. We have used the different variables and functions of the random module.

    Conclusion

    In this tutorial, we learned what a Python module is. We learned that a module is a file containing definitions of functions, classes, or variables that help us organize the code in a logical way and reuse it across different programs. There are three types of modules used in Python, including User-defined, Built-in and Third-party modules.

    We also discussed how to create and import a module in Python. We learned that there are multiple ways to import and use the functions of the modules. At last, we understood how to locate modules in Python and the use of the built-in dir() function.

  • Python Data Structures

    In Python, data structures are the building blocks used for organizing, processing, retrieving, and storing data so that it can be accessed more efficiently. Python is a high-level, object-oriented language that allows users to learn the fundamentals of data structures and their algorithms more simply.

    Data Structures in Python

    Python offers various data structures, such as:

    • List
    • Tuple
    • Set
    • Dictionary

    Let us discuss these data structures with examples:

    Lists

    Python Lists are used to store multiple items of different data types in a single variable. It works in the same manner as arrays, but with only one difference: in lists, not all the items need to be of the same data type.

    Lists are mutable (can be modified, deleted or replaced) and can contain duplicate items. A list works in the same way as an array in C, vectors in C++ or ArrayList in Java.

    Python List Example 

    Let us see a simple example showing how to create a list:

    Example

    # creating list  
    
    list_1 = ['Python App', 12, False, 1.6, 3e12]  
    
    print("List 1:", list_1)  
    
      
    
    # creating a nested list  
    
    list_2 = [['Learn', 'Python App'], 3, True, 'Hello', 1.69]  
    
    print("List 2:", list_2)

    Output:

    List 1: ['Python App', 12, False, 1.6, 3000000000000.0]
    List 2: [['Learn', 'Python App'], 3, True, 'Hello', 1.69]
    

    Explanation:

    In the above example, we have created a simple list using the square brackets ‘[]’. This list consists of different elements of data types. Similarly, we have created a nested list (a list within a list).

    Tuple

    Python Tuple is defined as a collection of objects. It works in a similar way like list with an only difference is that Tuples are immutable (which means once you create a tuple in Python, we cannot add, delete or modify and element in it). Just like a List, a Tuple can also contain elements of various types.

    In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of the data sequence.

    Python Tuple Example

    Here is a simple example to create a tuple.

    Example

    # creating tuple  
    
    tuple_1 = ('Python App', 19, True, 1.6, 5e3)  
    
    print("Tuple 1:", tuple_1)  
    
      
    
    # creating a nested tuple  
    
    tuple_2 = (('Hello', 'World'), 13, False, 'Python App', 6.9)  
    
    print("Tuple 2:", tuple_2)

    Output:

    Tuple 1: ('Python App', 19, True, 1.6, 5000.0)
    Tuple 2: (('Hello', 'World'), 13, False, 'Python App', 6.9)
    

    Explanation:

    In the above example, we have created a simple tuple using the parentheses ‘()’. This tuple consists of different elements of data types. Similarly, we have created a nested tuple (a tuple within a tuple).

    Set

    Python Set is a collection of unordered data used to store multiple elements in a single variable. Set is also mutable, which means once they create a set in Python, you cannot change or modify its elements.

    In Python sets, duplicity is not allowed; therefore, you cannot have two items with the same value, which helps eliminate duplicate entries. It is commonly used to include membership testing. Set uses the popular Hashing technique that permits operations like insertion, deletion, and traversal in O(1) time on average.

    Python Set Example

    Let us see a simple example showing how to create a set.

    Example

    # creating set  
    
    set_1 = {'hello', 'python app', 40, 21, 'hello', 19.2, False}  
    
    print("Set 1:", set_1)  
    
      
    
    # creating a set with a tuple an element  
    
    set_2 = {('learn', 'python app'), 10, 10, 'welcome', 13.6, True}  
    
    print("Set 2:", set_2)

    Output:

    Set 1: {False, 19.2, 'python app', 21, 'hello', 40}
    Set 2: {True, ('learn', 'python app'), 'welcome', 10, 13.6}
    

    Explanation:

    In the above example, we have created a set by enclosing some items with curly braces ‘{}’. Here, we can observe that the duplicate elements are eliminated from the set. Moreover, we can observed that the elements in the set are not ordered. We have created another set containing a tuple, an immutable sequence.

    Dictionary

    Python Dictionary is used to store data values key: value pair. It’s different from lists as it is ordered and changeable, and it doesn’t contain any duplicate elements. The values provided can be of any data type and may even contain duplicate data; however, the keys are immutable and should not contain duplicate values.

    In the Dictionary, indexing is done using keys. They internally use the concept of hashing and are of any hashable type (which means an object that can never change, like strings, numbers, tuples, etc.)

    Python Dictionary Example

    Let us see a simple example to create a dictionary.

    Example

    # creating dictionary  
    
    dict_1 = {  
    
        'name': 'Johnson',  
    
        'age' : 19,  
    
        'profession' : 'Software Developer',  
    
        'company' : 'python app',  
    
        'age' : 24  
    
              }  
    
    print("Dictionary 1:", dict_1)  
    
      
    
    # creating a nested dictionary  
    
    dict_2 = {  
    
        'name': 'Sachin',  
    
        'dob' : {  
    
            'date': 11,  
    
            'month': 'March',  
    
            'year': 1999  
    
        },  
    
        'profession' : 'Web Developer',  
    
        'company' : 'python app'  
    
        }  
    
    print("Dictionary 2:", dict_2)

    Output:

    Dictionary 1: {'name': 'Johnson', 'age': 24, 'profession': 'Software Developer', 'company': 'python app'}
    Dictionary 2: {'name': 'Sachin', 'dob': {'date': 11, 'month': 'March', 'year': 1999}, 'profession': 'Web Developer', 'company': 'Tpoint Tech'}
    

    Explanation:

    In the above example, we have created a dictionary by enclosing some ‘key: value’ pairs with curly braces ‘{}’. Here, we can see key ‘age’ is repeated, therefore the value of the first key is updated with the second value of the key as dictionary only contains unique keys. We have also created a nested dictionary (a dictionary as a value of another dictionary).

    String

    Python String are arrays of bytes representing Unicode characters. For example, “pythonapp” is a string containing the sequence of characters – ‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’, ‘a’, ‘p’, ‘p’.

    Python String Example

    Let’s understand this using an Example.

    Example

    # creating a string  
    
    my_str = "Learn Python App"  
    
    print("My String:", my_str)  
    
    print()  
    
      
    
    # performing operations on string  
    
    # given string  
    
    given_str = "Welcome to Learn Python App"  
    
    print("Given String:", given_str)  
    
    # printing results  
    
    print("Length of String:", len(given_str))  
    
    print("First Element of String:", given_str[0])  
    
    print("Last Element of String:", given_str[-1])  
    
    print("Fourth Element of String:", given_str[3])

    Output:

    My String: Learn Python App
    
    Given String: Welcome to Learn Python App
    Length of String: 22
    First Element of String: W
    Last Element of String: h
    Fourth Element of String: c
    

    Explanation:

    Here, we have created a string by enclosing a text with double quotation marks (“…”). We have also performed some operations on string, such as finding its length and also printing the different elements of the string.

    Collections Module

    Python Collection Module acts as a container that provides various in-built datatypes. Let’s understand them one by one.

    S. No.Data StructuresDescription
    1CountersThe Python counter is a sub-class of the dictionary. It is used to keep the count of the elements in an iterable in the form of an unordered dictionary where the key represents the element in the iterable and value represents the count of that element in the iterable.
    2OrderedDictPython OrderedDict is like a dictionary, with the only difference being that it to maintain the insertion order of keys in a dictionary.
    3DequePython Deque stands for Doubly Ended Queue. It is a list-like container used for accessing fast append and pop operations from both sides of the container. It supports both FIFO (First In, First Out) and LIFO (Last In, First Out) operations.
    4ChainMapPython ChainMap encapsulates different dictionaries into a single variable. It finds the key by searching all the dictionaries one by one unless the required value is found.
    5UserDictPython UserDict wraps all the dictionary objects. It acts as a container used by Python developer when they want to create their dictionary with some modified or new functionality.

    Conclusion

    In this tutorial, we explored the fundamental of data structures in Python that are used for data management and manipulation. From built-in structures like ListsTuplesDictionariesSets and Strings to more specialized structures like the Collections Module, each have its unique purpose in programming.

    Understanding these data structures are very useful as it improves the performance and clarity of your code. Applying data structures also strengthens your problem-solving capabilities in Python.

  • Python Data Structures

    In Python, data structures are the building blocks used for organizing, processing, retrieving, and storing data so that it can be accessed more efficiently. Python is a high-level, object-oriented language that allows users to learn the fundamentals of data structures and their algorithms more simply.

    Data Structures in Python

    Python offers various data structures, such as:

    • List
    • Tuple
    • Set
    • Dictionary

    Let us discuss these data structures with examples:

    Lists

    Python Lists are used to store multiple items of different data types in a single variable. It works in the same manner as arrays, but with only one difference: in lists, not all the items need to be of the same data type.

    Lists are mutable (can be modified, deleted or replaced) and can contain duplicate items. A list works in the same way as an array in C, vectors in C++ or ArrayList in Java.

    Python List Example 

    Let us see a simple example showing how to create a list:

    Example

    # creating list  
    
    list_1 = ['Learn', 12, False, 1.6, 3e12]  
    
    print("List 1:", list_1)  
    
      
    
    # creating a nested list  
    
    list_2 = [['Learn python app'], 3, True, 'Hello', 1.69]  
    
    print("List 2:", list_2)

    Output:

    List 1: ['python app', 12, False, 1.6, 3000000000000.0]
    List 2: [['Learn', 'python app'], 3, True, 'Hello', 1.69]
    

    Explanation:

    In the above example, we have created a simple list using the square brackets ‘[]’. This list consists of different elements of data types. Similarly, we have created a nested list (a list within a list).

    Tuple

    Python Tuple is defined as a collection of objects. It works in a similar way like list with an only difference is that Tuples are immutable (which means once you create a tuple in Python, we cannot add, delete or modify and element in it). Just like a List, a Tuple can also contain elements of various types.

    In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of the data sequence.

    Python Tuple Example

    Here is a simple example to create a tuple.

    Example

    # creating tuple  
    
    tuple_1 = ('python app', 19, True, 1.6, 5e3)  
    
    print("Tuple 1:", tuple_1)  
    
      
    
    # creating a nested tuple  
    
    tuple_2 = (('Hello', 'World'), 13, False, 'python app', 6.9)  
    
    print("Tuple 2:", tuple_2)

    Output:

    Tuple 1: ('python app', 19, True, 1.6, 5000.0)
    Tuple 2: (('Hello', 'World'), 13, False, 'python app', 6.9)

    Explanation:

    In the above example, we have created a simple tuple using the parentheses ‘()’. This tuple consists of different elements of data types. Similarly, we have created a nested tuple (a tuple within a tuple).

    Set

    Python Set is a collection of unordered data used to store multiple elements in a single variable. Set is also mutable, which means once they create a set in Python, you cannot change or modify its elements.

    In Python sets, duplicity is not allowed; therefore, you cannot have two items with the same value, which helps eliminate duplicate entries. It is commonly used to include membership testing. Set uses the popular Hashing technique that permits operations like insertion, deletion, and traversal in O(1) time on average.

    Python Set Example

    Let us see a simple example showing how to create a set.

    Example

    # creating set  
    
    set_1 = {'hello', 'python app', 40, 21, 'hello', 19.2, False}  
    
    print("Set 1:", set_1)  
    
      
    
    # creating a set with a tuple an element  
    
    set_2 = {('python app), 10, 10, 'welcome', 13.6, True}  
    
    print("Set 2:", set_2)

    Output:

    Set 1: {False, 19.2, 'python app', 21, 'hello', 40}
    Set 2: {True, ('tpoint', 'tech'), 'welcome', 10, 13.6}
    

    Explanation:

    In the above example, we have created a set by enclosing some items with curly braces ‘{}’. Here, we can observe that the duplicate elements are eliminated from the set. Moreover, we can observed that the elements in the set are not ordered. We have created another set containing a tuple, an immutable sequence.

    Dictionary

    Python Dictionary is used to store data values key: value pair. It’s different from lists as it is ordered and changeable, and it doesn’t contain any duplicate elements. The values provided can be of any data type and may even contain duplicate data; however, the keys are immutable and should not contain duplicate values.

    In the Dictionary, indexing is done using keys. They internally use the concept of hashing and are of any hashable type (which means an object that can never change, like strings, numbers, tuples, etc.)

    Python Dictionary Example

    Let us see a simple example to create a dictionary.

    Example

    # creating dictionary  
    
    dict_1 = {  
    
        'name': 'Johnson',  
    
        'age' : 19,  
    
        'profession' : 'Software Developer',  
    
        'company' : ' python app ',  
    
        'age' : 24  
    
              }  
    
    print("Dictionary 1:", dict_1)  
    
      
    
    # creating a nested dictionary  
    
    dict_2 = {  
    
        'name': 'Sachin',  
    
        'dob' : {  
    
            'date': 11,  
    
            'month': 'March',  
    
            'year': 1999  
    
        },  
    
        'profession' : 'Web Developer',  
    
        'company' : ' python app '  
    
        }  
    
    print("Dictionary 2:", dict_2)

    Output:

    Dictionary 1: {'name': 'Johnson', 'age': 24, 'profession': 'Software Developer', 'company': ' python app '}
    Dictionary 2: {'name': 'Sachin', 'dob': {'date': 11, 'month': 'March', 'year': 1999}, 'profession': 'Web Developer', 'company': ' python app '}
    

    Explanation:

    In the above example, we have created a dictionary by enclosing some ‘key: value’ pairs with curly braces ‘{}’. Here, we can see key ‘age’ is repeated, therefore the value of the first key is updated with the second value of the key as dictionary only contains unique keys. We have also created a nested dictionary (a dictionary as a value of another dictionary).

    String

    Python String are arrays of bytes representing Unicode characters. For example, “pythonapp” is a string containing the sequence of characters – ‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’, ‘a’, ‘p, ‘p’, .

    Python String Example

    Let’s understand this using an Example.

    Example

    # creating a string  
    
    my_str = "Learn python app"  
    
    print("My String:", my_str)  
    
    print()  
    
      
    
    # performing operations on string  
    
    # given string  
    
    given_str = "Welcome to Learn python app  
    
    print("Given String:", given_str)  
    
    # printing results  
    
    print("Length of String:", len(given_str))  
    
    print("First Element of String:", given_str[0])  
    
    print("Last Element of String:", given_str[-1])  
    
    print("Fourth Element of String:", given_str[3])

    Output:

    My String: Learn python app
    
    Given String: Welcome to Learn python app
    Length of String: 22
    First Element of String: W
    Last Element of String: h
    Fourth Element of String: c
    

    Explanation:

    Here, we have created a string by enclosing a text with double quotation marks (“…”). We have also performed some operations on string, such as finding its length and also printing the different elements of the string.

    Collections Module

    Python Collection Module acts as a container that provides various in-built datatypes. Let’s understand them one by one.

    S. No.Data StructuresDescription
    1CountersThe Python counter is a sub-class of the dictionary. It is used to keep the count of the elements in an iterable in the form of an unordered dictionary where the key represents the element in the iterable and value represents the count of that element in the iterable.
    2OrderedDictPython OrderedDict is like a dictionary, with the only difference being that it to maintain the insertion order of keys in a dictionary.
    3DequePython Deque stands for Doubly Ended Queue. It is a list-like container used for accessing fast append and pop operations from both sides of the container. It supports both FIFO (First In, First Out) and LIFO (Last In, First Out) operations.
    4ChainMapPython ChainMap encapsulates different dictionaries into a single variable. It finds the key by searching all the dictionaries one by one unless the required value is found.
    5UserDictPython UserDict wraps all the dictionary objects. It acts as a container used by Python developer when they want to create their dictionary with some modified or new functionality.

    Conclusion

    In this tutorial, we explored the fundamental of data structures in Python that are used for data management and manipulation. From built-in structures like ListsTuplesDictionariesSets and Strings to more specialized structures like the Collections Module, each have its unique purpose in programming.

    Understanding these data structures are very useful as it improves the performance and clarity of your code. Applying data structures also strengthens your problem-solving capabilities in Python.

  • Difference between Set and Dictionary in Python

    In Python, sets and dictionaries are the built-in data structures. A set is an unindexed and unordered collection that stores unique items. On the other hand, a dictionary is an unordered and indexed collection that stores data in ‘key-value’ pairs.

    Even though these two are used for storing data collections and share some similarities, they differ significantly in terms of structure, behavior, and applications.

    What is a Set in Python?

    In Python, A set is one of the four built-in data types used for storing collections, along with lists, tuples, and dictionaries. It is an unordered collection of unique items. Sets are considered mutable, which allows us to add or remove elements even after the set has been created.

    Sets are represented using curly braces {}, and the elements in the set are separated by commas. Usually, the set() function is used to generate an empty set, and {} is used to create an empty dictionary.

    Characteristics of a Set

    Here are some major characteristics of Python Set:

    • Unordered: Elements in a set do not have any particular order.
    • Mutable: Elements can be added or removed from a set after its creation (e.g., with add(), remove(), discard()).
    • No Duplicates: Sets have unique elements; duplicates are simply ignored (if present).

    Let us see an example to create sets in Python.

    Difference between Set and Dictionary in Python

    Python Set Example

    Let us see an example to create sets in Python.

    Example

    # creating the first set  
    # Isme "Learn python App" ek single element ki tarah treat hoga
    first_set = set(("Learn python App", 14, (1, 2, 3)))  
    
    # printing the first set  
    print(first_set)  
    
    # creating the second set  
    # set() function string ke har unique character ko alag-alag kar dega
    second_set = set("Learn python App")  
    
    # printing the second set  
    print(second_set)

    Output:

    {'Learn python App', (1, 2, 3), 14}
    {'p', 'n', 'y', 'e', 'h', 'o', 'r', 'L', 't', 'a', ' ', 'A'}

    What is a Dictionary in Python?

    Dictionary is a built-in data type used in Python to store data in the form of ‘key: value’ pairs. Dictionaries are unordered (starting from Python 3.7, they preserve insertion order), mutable, and indexed collections where each key is unique and maps to a value. It is generally used to store related data, such as information associated with a specific entity or object, where the value can be retrieved easily on the basis of the key.

    We generally use dictionaries to store related data, such as information associated with a particular object or entity, where it can easily be retrieved based on its key.

    Characteristics of a Dictionary

    Python dictionary comes up with several features, which are as follows:

    Difference between Set and Dictionary in Python
    • Unordered: Dictionaries do not follow a particular order to store items. However, starting from Python 3.7+, the Order is maintained when inserting key-value pairs into the dictionary.
    • Mutable: One can add, delete, or change key-value pairs after the dictionary is created.
    • Unique Keys: A dictionary’s keys must be distinct (unique). If you attempt to insert a new value with a present key, the value that is present with the key will be replaced.
    • Key-Based Access: Elements are accessed by their keys, not by their indices. This feature helps in finding the items based on the key.

    Python Dictionary Example

    Let us see an example to create dictionaries in Python.

    Example

    # simple program to create a dictionary in Python    
    
        
    
    # creating a dictionary    
    
    employee_data = {    
    
        'full_name': 'Irfan Khan',    
    
        'employee_id': 1023,    
    
        'department': 'IT'    
    
    }    
    
        
    
    # printing result    
    
    print("Employee Data:", employee_data)    
    
    print("Data Type:", type(employee_data))

    Output:

    Employee Data: {'full_name': 'Irfan Khan', 'employee_id': 1023, 'department': 'IT'}
    Data Type: <class 'dict'>

    Key Differences between Sets and Dictionaries

    The following are key differences between Sets and Dictionaries in Python:

    FeatureSetDictionary
    DefinitionSet is an unordered collection of unique elements.Dictionary is an ordered collection of key-value pairs.
    RepresentationCurly braces {}Curly braces {}, but with key-value pairs.
    OrderedNoYes (since Python 3.7)
    DuplicatesNot Allowed (only unique elements are stored)Not Allowed (keys must be unique; values can be duplicated)
    HashingHashable (if all elements within the set are hashable)Not directly hashable (but its keys() and items() views can behave like sets for some operations in later Python versions)
    MutableYes (elements can be added or removed)Yes (key: value pairs can be added, removed, or values modified)
    Use CaseStoring unique items, membership testing, set algebra operations, and removing duplicates.Mapping keys to values, efficient lookups by key, and representing structured or labelled data.
  • Difference between List, Set, Tuple, and Dictionary in Python

    List, Set, Tuple, and Dictionary are widely used data structures in Python. These data structures play a crucial role in maintaining and organizing data. In order to write efficient and effective Python code, one should know the key differences between these data structures.

    What is a List?

    A list in Python is a built-in data structure that allows us to store multiple items in a single variable. Lists are one of the widely used data structures in Python because they are mutable, ordered, and can hold different types of elements.

    Lists offer a flexible way to handle collections of data and come with many useful built-in methods. Lists are usually defined by enclosing the collection of elements separated by commas with square brackets [].

    Characteristics of a List

    Several characteristics of List in Python are as follows:

    • Ordered: Elements are stored in a particular order, and their position (index) is significant.
    • Mutable: One can modify the elements of a list once it’s created (e.g., using append(), insert(), remove(), pop()).
    • Allows Duplicates: There can be several instances of the same element in a list. This means that the element can be repeated n times.
    • Indexed Access: Elements are accessed by their index (which is generally an integer); the index of the first element is 0.
    Difference between List, Set, Tuple, and Dictionary in Python

    Python List Example

    Let us see an example of a list in Python.

    Example

    # simple python program to create a list  
    
      
    
    # creating a list  
    
    lst_1 = [12, 'Learn python App', 3.61, True]  
    
      
    
    # printing the list  
    
    print("List :", lst_1)  
    
      
    
    # printing its data type  
    
    print(type(lst_1))

    Output:

    List : [12, 'Learn python App', 3.61, True]
    <class 'list'>

    Explanation:

    In this example, we have created a list by enclosing several elements of different data types with square brackets [].

    What is a Set?

    set is an unordered collection. It means that sets do not have any particular order for elements. Sets always store the distinct elements; they automatically eliminate any duplicate entries (if they are present in the set).

    Sets are represented using curly braces {}, and the elements in the set are separated by commas. Usually, the set() function is used to generate an empty set, and {} is used to create an empty dictionary.

    Characteristics of a Set

    Several characteristics of a set in Python are as follows:

    • Unordered: Elements in a set do not have any particular order.
    • Mutable: Elements can be added or removed from a set after its creation (e.g., with add(), remove(), discard()).
    • No Duplicates: Sets have unique elements; duplicates are simply ignored (if present).
    Difference between List, Set, Tuple, and Dictionary in Python

    Python Set Example

    The following is a simple example of a set in Python.

    Example

    # creating the first set  
    # Humne "TpointTech" ko "Learn python App" se replace kar diya hai
    first_set = set(("Learn python App", 14, (1, 2, 3)))  
    
    # printing the first set  
    print(first_set)  
    
      
    # creating the second set  
    # Yahan bhi string badal di gayi hai
    second_set = set("Learn python App")  
    
    # printing the second set  
    print(second_set)

    Output:

    {14, (1, 2, 3), 'Learn python App'}
    {' ', 'n', 'p', 'r', 'y', 't', 'A', 'h', 'o', 'e', 'L', 'a'}

    Explanation:

    In this example, we have created a set by enclosing several elements with curly braces {}.

    What is a Tuple?

    Tuple is a built-in data structure in Python used to store a collection of objects. It is quite similar to a list in terms of indexing, nesting, and repetition. But tuples are immutable, meaning we cannot change their elements once created. A tuple is created by enclosing the elements separated by commas within parentheses ().

    Characteristics of a Tuple

    Several characteristics of a Tuple  in Python are as follows:

    • Ordered: Items are stored in a definite order.
    • Immutable: Once a tuple is made, its items cannot be altered (no addition, deletion, or modification).
    • Supports Duplicates: A tuple may have more than one occurrence of the same element. It means that an element can be present n times.
    • Indexed Access: Access to elements is possible using their indexes, and the index starts with 0.
    • Used Usually with Fixed Collections: Tuples are used to represent collections of records that need not be changed in the future, e.g., coordinates or records.
    • Slightly Smaller than Lists: As tuples are immutable, they occupy less memory than lists.
    Difference between List, Set, Tuple, and Dictionary in Python

    Python Tuple Example

    We will now look at an example of a tuple in Python.

    Example

    # simple python program to create a tuple    
    
        
    
    # creating a tuple    
    
    tpl_1 = (19, 'Python', 7.8, True)    
    
        
    
    # printing the tuple    
    
    print("Tuple :", tpl_1)    
    
        
    
    # printing type of list    
    
    print(type(tpl_1))

    Output:

    Tuple : (19, 'Python', 7.8, True)
    <class 'tuple'>

    Explanation:

    In this example, we have created a set by enclosing several elements of different data types with curly braces ().

    What is a Dictionary?

    A Dictionary is a built-in data structure in Python that we use to store data in ‘key: value’ pairs. The dictionary is an unordered (since Python 3.7, insertion is ordered), mutable, and indexed collection where each key is unique and maps to the associated value. We generally use dictionaries to store related data, such as information associated with a particular object or entity, where it can easily be retrieved based on its key.

    Characteristics of a Dictionary

    Several chacteristics of a dictionary in Python are as follows:

    • Unordered: Dictionaries do not follow a particular order to store items. However, starting from Python 3.7+, the Order is maintained when inserting key-value pairs into the dictionary.
    • Mutable: One can add, delete, or change key-value pairs after the dictionary is created.
    • Unique Keys: A dictionary’s keys must be distinct (unique). If you attempt to insert a new value with a present key, the value associated with the key will be replaced.
    • Key-Based Access: Elements are accessed by their keys, not by their indices. This feature helps in finding the items based on the key.
    Difference between List, Set, Tuple, and Dictionary in Python

    Python Dictionary Example

    Here is a simple example of a dictionary in Python.

    Example

    # simple python program to create a dictionary  
    
      
    
    # creating a dictionary  
    
    dict_1 = {'emp_id': 1001, 'name': 'Irfan', 'job_profile': 'Software Developer'}  
    
      
    
    # printing the dictionary  
    
    print("Dictionary :", dict_1)  
    
      
    
    # printing type of list  
    
    print(type(dict_1))

    Output:

    Dictionary : {'emp_id': 1001, 'name': 'Irfan', 'job_profile': 'Software Developer'}
    <class 'dict'>

    Explanation:

    In this example, we have created a dictionary consisting of multiple ‘key: value’ pairs separated by commas and enclosed with curly braces {}.

    Key Differences between List, Set, Tuple, and Dictionary

    The following are key differences between Lists, Sets, Tuples, and Dictionaries in Python:

    FeatureListSetTupleDictionary
    OrderedYesNoYesYes (since Python 3.7)
    Mutable (Container)Yes (elements can be added, removed, or modified)Yes (elements can be added or removed)No (elements cannot be changed after creation)Yes (key-value pairs can be added, removed, or values modified)
    Mutable (Elements)Yes (if the elements themselves are mutable)Yes (if the elements themselves are mutable)No (elements themselves cannot be changed if the tuple is immutable)Yes (values can be mutable; keys must be immutable)
    DuplicatesAllowedNot Allowed (only unique elements are stored)AllowedNot Allowed (keys must be unique; values can be duplicated)
    Indexing/AccessYes (integer-based index, starting from 0)No (elements are not ordered and cannot be accessed by index)Yes (integer-based index, starting from 0)Yes (key-based access; values are retrieved using their unique keys)
    HashingNot Hashable (cannot be used as keys in dictionaries or elements in sets)Hashable (if all elements within the set are hashable)Hashable (if all elements within the tuple are hashable)Not directly hashable (but its keys() and items() views can behave like sets for some operations in later Python versions)
    Syntax[item1, item2, …]{item1, item2, …} (empty set: set())(item1, item2, …) (single element tuple: (item1,)){key1: value1, key2: value2, …}
    Common Methodsappend(), extend(), insert(), remove(), pop(), index(), count(), sort(), reverse(), clear(), copy()add(), remove(), discard(), pop(), clear(), copy(), union(), intersection(), difference(), symmetric_difference()count(), index()get(), keys(), values(), items(), update()pop(), popitem(), clear(), copy(), setdefault()
    Memory OverheadGenerally higher than tuples for the same number of elements due to dynamic resizing capabilities.Can have overhead due to the need for hash table management to ensure uniqueness.Generally lower than lists for the same number of elements due to fixed size.Can have significant overhead due to the storage of both keys and values and the underlying hash table.
    Use CasesOrdered collections needing modification, maintaining order of insertion, and variable-length collections.Storing unique items, membership testing, set algebra operations, and removing duplicates.Representing fixed data structures, ensuring data integrity, used as keys in dictionaries (if elements are hashable), and returning multiple values.It maps the key to their values, efficient lookups by key and represents structured or labeled data.

    Conclusion

    We have learnt a lot about the differences between List, Set, Dictionary, and Tuple. The List, Tuple, and Dictionary(from Python version 3.7) are ordered, whereas the set is unordered. Similarly, the List, Set, and Dictionary are mutable. We have discussed each and every criterion in detail.

    We still feel that there’s a lot to come; features and objectives might change with upcoming Python versions.

  • Difference between List and Dictionary in Python

    Lists and dictionaries are two of the data types in Python that are known as collections of data. A list is an ordered collection that stores items using index numbers, making it ideal to manage data sequences. On the other hand, a dictionary stores data in key-value pairs, which allows fast and flexible access using unique keys.

    What is a List in Python?

    In Python, A List is an ordered, mutable collection of elements. It allows us to perform various modifications such as adding, removing, or changing elements. We can store any type of data in a list, including numbers, strings, or even a list.

    Difference between List and Dictionary in Python

    Characteristics of Lists:

    Several characteristics of Lists in Python are as follows:

    • Ordered: In this, A List maintains a particular order of its elements with an index starting from 0.
    • Mutable: In the Mutable data type, we can edit or make changes to the elements.
    • Dynamic: The List can grow or shrink in size dynamically.
    • Supports Multiple Data Types: A list can contain elements of various and distinct data types.
    • The List uses square brackets ([])for declaration.

    Python List Example

    Let us take an example to demonstrate the List in Python.

    Example

    # Creating a list    
    
    my_list = [14, 'banana', 8.2]    
    
      
    
    # printing the list      
    
    print("Initialized list:", my_list)      
    
    print("Data Type:", type(my_list))

    Output:

    Initialized list: [14, 'banana', 8.2]
    Data Type: <class 'list'>

    Explanation:

    In the following example, we have created a list using square brackets [] and printed it. We can observe that the initialized list consists of different data types like integer, string, and float.

    What is a Python Dictionary?

    Dictionary is a built-in data type used in Python to store data in the form of ‘key: value’ pairs. Dictionaries are unordered (starting from Python 3.7, they preserve insertion order), mutable, and indexed collections where each key is unique and maps to a value. It is generally used to store related data, such as information associated with a specific entity or object, where the value can be retrieved easily on the basis of the key.

    Difference between List and Dictionary in Python

    Characteristics of a Dictionary:

    Several characteristics of a Dictionary in Python are as follows:

    • Unordered: In this, A Dictionary does not maintain a particular order.
    • Mutable: In the Mutable data type, we can edit or make changes to the elements.
    • Keys-Value Pairs: The values in the Dictionary are stored as a collection of unique keys, and every key has its unique value.
    • Dynamic: The List can grow or shrink in size dynamically.
    • Supports Multiple Data Types: A list can contain elements of various and distinct data types.
    • Unique and Immutable Keys:The Dictionary keys are unique and immutable, such as strings, integers, and floats.
    • The Dictionary uses curly brackets ({})for declaration.

    Python Dictionary Example

    Let us take an example to demonstrate the Dictionary in Python.

    Example

    # Creating a dictionary  
    
    my_dict = {'name': 'John', 'age': 23, 'salary': 69000}  
    
      
    
    # printing the dictionary    
    
    print("Initialized dictionary:", my_dict)    
    
    print("Data Type:", type(my_dict))

    Output:

    Initialized dictionary: {'name': 'John', 'age': 23, 'salary': 69000}
    Data Type: <class 'dict'>
    

    Explanation:

    In this example, we have created a dictionary consisting of several key: value pairs separated by commas enclosed with the curly brackets {}.

    Key Differences between Lists and Dictionaries

    The following are key differences between Lists and Dictionaries in Python:

    FeatureListDictionary
    DefinitionOrdered collection of itemsUnordered (insertion-ordered from Python 3.7+) key: value pairs
    Syntax[] (Square brackets){} (Curly braces)
    Data AccessBy index (for example, my_list[0])By key (for example, my_dict[‘a’])
    IndexingUses numeric index (0, 1, 2, …)Uses keys (can be strings, numbers, etc.)
    OrderingMaintains order of itemsMaintains insertion order (Python 3.7+)
    MutabilityMutable (can change items)Mutable (can add, remove, or change key: value pairs)
    DuplicatesAllows duplicate valuesKeys must be unique; values can be duplicated
    Best Used ForCollections of similar items (like a list of numbers)Related data pairs (like name: age, product: price, etc.)
    IterationIterates over valuesIterates over keys (or values/items using .values() or .items())
    Memory UsageLess than dictionary (generally)Slightly more due to key: value pair structure
    Search Time ComplexityO(n) slower for lookupsO(1) on average faster with hash table
    Nested StructuresCan contain other listsCan contain other dictionaries or mixed data types