Category: Python Built-in Functions

  • Python iter() Function

    The python iter() function is used to return an iterator object. It creates an object which can be iterated one element at a time.

    Python iter() Function Syntax

    It has the following syntax:

    iter(object, sentinel)  

    Parameters

    • object: An iterable object.
    • sentinel (optional): It is a special value that represents the end of a sequence.

    Return

    It returns an iterator object.

    Python iter() Function Example

    The below example shows the working of the iter() function in Python.

    # list of numbers  
    
    list = [1,2,3,4,5]  
    
      
    
    listIter = iter(list)  
    
      
    
    # prints '1'  
    
    print(next(listIter))  
    
      
    
    # prints '2'  
    
    print(next(listIter))  
    
      
    
    # prints '3'  
    
    print(next(listIter))  
    
      
    
    # prints '4'  
    
    print(next(listIter))  
    
      
    
    # prints '5'  
    
    print(next(listIter))

    Output:

    1
    2
    3
    4
    5
    

    Explanation:

    In the above example, iter() function converts an list iterable to an iterator.

  • Python hasattr() Function

    The python hasattr() function returns true if an object has given named attribute. Otherwise, it returns false.

    Python hasattr() Function Syntax

    It has the following syntax:

    hasattr(object, attribute)  

    Parameters

    • object: It is an object whose named attribute is to be checked.
    • attribute: It is the name of the attribute that you want to search.

    Return

    It returns true if an object has given named attribute. Otherwise, it returns false.

    Python hasattr() Function Example

    The below example shows the working of hasattr() function in Python.

    class Employee:  
    
        age = 21  
    
        name = 'Phill'  
    
      
    
    employee = Employee()  
    
      
    
    print('Employee has age?:', hasattr(employee, 'age'))  
    
    print('Employee has salary?:', hasattr(employee, 'salary'))

    Output:

    Employee has age?: True
    Employee has salary?: False
    

    Explanation:

    In the above example, we have created a class named as Employee, then we create the object of the Employee class, i.e., employee. The hasattr(employee, ‘age’) returns the true value as the employee object contains the age named attribute, while hasattr(employee, ‘salary’)) returns false value as the employee object does not contain the salary named attribute.

  • Python globals() Function

    The python globals() function returns the dictionary of the current global symbol table. A Symbol table is defined as a data structure which contains all the necessary information about the program. It includes variable names, methods, classes etc.

    Python globals() Function Syntax

    It has the following syntax:

    globals()  

    Parameters

    It does not contain any parameters.

    Return

    It returns the dictionary of the current of the current global symbol table.

    Python globals() Function Example

    The below example shows how to modify a global variable using the globals() function in Python.

    age = 22  
    
      
    
    globals()['age'] = 22  
    
    print('The age is:', age)

    Output:

    The age is: 22
    

    Explanation:

    In the above example, we take a variable name(age) and make it as a global variable and this global variable is being modified by using globals() method.

  • Python getattr() Function

    The python getattr() function returns the value of a named attribute of an object. If it is not found, it returns the default value.

    Python getattr() Function Syntax

    It has the following syntax:

    getattr(object, attribute, default)  

    Parameters

    • object: An object whose named attribute value is to be returned.
    • attribute: Name of the attribute of which you want to get the value.
    • default (optional): It is the value to return if the named attribute does not found.

    Return

    It returns the value of a named attribute of an object. If it is not found, it returns the default value.

    Different Examples for Python getattr() Function

    Here, we are going to discuss several examples for Python getattr() Function.

    Python getattr() Function Example 1

    The below example shows the working of the getattr() function in Python.

    class Details:  
    
        age = 22  
    
        name = "Phill"  
    
      
    
    details = Details()  
    
    print('The age is:', getattr(details, "age"))  
    
    print('The age is:', details.age)

    Output:

    The age is: 22
    The age is: 22
    

    Explanation: In the above example, we take a class named as Details that consists of some variables i.e. age, name etc. and returns the value of named attributes of an object in output.

    Python getattr() Function Example 2

    The below example shows the working of getattr() when named attribute is not found.

    class Details:  
    
        age = 22  
    
        name = "Phill"  
    
      
    
    details = Details()  
    
      
    
    # when default value is provided  
    
    print('The gender is:', getattr(details, 'gender', 'Male'))  
    
      
    
    # when no default value is provided  
    
    print('The gender is:', getattr(details, 'gender'))

    Output:

    The gender is: Male
    AttributeError: 'Details' object has no attribute 'gender'
  • Python frozenset() Function

    The python frozenset() function returns an immutable frozenset object initialized with elements from the given iterable.

    Python frozenset() Function Syntax

    It has the following Syntax:

    frozenset(iterable)  

    Parameters

    • iterable: An iterable object such as list, tuple etc.

    Return

    It returns an immutable frozenset object initialized with elements from the given iterable.

    Different Examples for Python frozenset() Function 

    Here, we are going to discuss several examples for Python frozenset() function.

    Python frozenset() Function Example 1

    The below example shows the working of the frozenset() function in Python.

    # tuple of letters  
    
    letters = ('m', 'r', 'o', 't', 's')  
    
      
    
    fSet = frozenset(letters)  
    
    print('Frozen set is:', fSet)  
    
    print('Empty frozen set is:', frozenset())

    Output:

    Frozen set is: frozenset({'o', 'm', 's', 'r', 't'})
    Empty frozen set is: frozenset()
    

    Explanation:

    In the above example, we take a variable that consists tuple of letters and returns an immutable frozenset object.

    Python frozenset() Function Example 2

    The below example shows the working of frozenset() with dictionaries.

    # random dictionary  
    
    person = {"name": "Phill", "age": 22, "sex": "male"}  
    
      
    
    fSet = frozenset(person)  
    
    print('Frozen set is:', fSet)

    Output:

    Frozen set is: frozenset({'name', 'sex', 'age'})
  • Python format() Function

    The python format() function returns a formatted representation of the given value.

    Python format() Function Syntax

    It has the following syntax:

    format(value, format)  

    Parameters

    • value: It is the value that needs to be formatted.
    • format: It is the specification on how the value should be formatted.

    Return

    It returns a formatted representation of the given value.

    Python format() Function Example

    The below example shows a number of formatting with format() function in Python.

    # d, f and b are a type  
    
      
    
    # integer  
    
    print(format(123, "d"))  
    
      
    
    # float arguments  
    
    print(format(123.4567898, "f"))  
    
      
    
    # binary format  
    
    print(format(12, "b"))

    Output:

    123
    123.456790
    1100
    

    Explanation: The above example returns a formatted representation of the values.

  • Python float() Function

    The python float() function returns a floating-point number from a number or string. A floating-point number, or float, is a mathematical value that contains a decimal point. Floats can be positive or negative and can address both whole numbers and fractional values. In Python, the float() function is utilised to switch a value completely to a float.

    Python float() Function Syntax

    It has the following syntax:

    float(value)  

    Parameters

    • value: It can be a number or string that converts into a floating point number.

    Return

    It returns a floating point number.

    Different Examples for Python float() Function

    Here, we are going to take several examples to demonstrate the Python float() Function.

    Python float() Function Example 1

    The below example shows the working of the float() function in Python.

    # Python example program for float() function in Python  
    
    # for integers    
    
    a = float(2)  
    
    print(a)    
    
        
    
    # for floats    
    
    b = float(" 5.90 ")  
    
    print(b)    
    
        
    
    # for string floats    
    
    c = float("-24.17")  
    
    print(c)    
    
        
    
    # for string floats with whitespaces    
    
    d = float(" -17.15\n ")  
    
    print(d)    
    
      
    
    # string float error    
    
    e = float(" xyz ")    
    
    print(e)

    Output:

    2.0
    5.90
    -24.17
    -17.15
    ValueError: could not convert string to float: ' xyz '
    

    Explanation: In the above example, we have given different types of inputs, like an integer, a float value, and a string value. When the argument is passed to the float() function, the output is returned in the form of a floating value.

    Note: The important point to note is that the float() method converts only integers and strings into floating-point values. All the other arguments, like list, tuple, dictionary, and None values, result in TypeErrors.

    Python float() Function Example 2

    Let us take an example to demonstrate the float() function in Python.

    # Python program for float() function  
    
    # List  
    
    list = float([11, 24, 38, 76, 100])  
    
    # Tuple  
    
    tuple = float(( 10, 20, 30, 40, 50 ))  
    
    # Dictionary  
    
    dictionary = float({ " ram ": 1000, " bheem ": 2000})  
    
    # None  
    
    value = float(None)  
    
      
    
    print(list)  
    
    print(tuple)  
    
    print(dictionary)  
    
    print(value)

    Output:

    TypeError: float() argument must be a string or a number, not ' list '
    TypeError: float() argument must be a string or a number, not ' tuple '
    TypeError: float() argument must be a string or a number, not ' dict '
    TypeError: float() argument must be a string or a number, not ' NoneType '
    

    Conclusion

    To conclude, the float() function in Python is utilised to change a number or a string that addresses a number to a floating-point value. When utilised accurately, the function can assist you with changing information between various mathematical configurations and performing number-crunching tasks that require floating-point accuracy.

  • Python eval() Function

    In Python, the eval() function is an underlying Python function that evaluates a string as a Python expression. It takes a single parameter, which is a string that addresses a Python expression. The eval() function then evaluates this expression and returns the outcome. The python eval() function parses the expression passed to it and runs python expression(code) within the program.

    The eval() function is in many cases used in Python to execute dynamically produced code. For instance, on the off chance that you have a string that contains a numerical expression, you can use the eval() function to evaluate that expression and return the outcome.

    Python eval() Function Syntax

    It has the following syntax:

    eval(expression, globals, locals)  

    Parameters

    • expression: The string is parsed and evaluated as a Python expression.
    • globals (optional): A dictionary that specifies the available global methods and variables.
    • locals (optional): It is an another dictionary which is commonly used for mapping type in Python.

    Return

    It returns the result evaluated from the expression.

    Different Examples for Python eval() Function

    Here, we are going to discuss several examples of Python eval() Function.

    Python eval() Function Example 1

    The below example shows the working of the eval() function in Python.

    # Python program for eval() function  
    
    # Declaring variables  
    
    x = 15  
    
    y = 25  
    
    result = eval('x + y')  
    
    # print result  
    
    print(result)

    Output:

    40
    

    Explanation:

    In this example, we have defined two variables x and y and introduced them with the values 15 and 25, separately. We then, at that point, call the eval() function with the string ‘x + y’ as the expression. The eval() function evaluates this expression as the sum of the values of x and y, which is 40. At last, we print the outcome using the print() function.

    Python eval() Function Example 2

    As well as accepting a single parameter that addresses a Python expression as a string, the eval() function likewise permits us to determine the context where the expression ought to be evaluated. You can use the locals and globals contentions to pass in dictionaries references that address the local and global namespaces, separately.

    Here is an example that shows the way that you can use locals and globals with the eval() function:

    # Python program for eval() function  
    
    x = 5  
    
    y = 15  
    
    expr = 'x + y'  
    
    result = eval(expr, globals(), locals())  
    
    print(result)

    Output:

    20
    

    Explanation:

    In this example, we have defined two variables x and y, and a string expr that contains a Python expression. We then call the eval() function with the globals() and locals() functions as contentions, which address the global and local namespaces, separately. The eval() function evaluates the expression ‘x + y’ utilizing the globals() and locals() namespaces and returns the outcome, which is 20.

    Python eval() Function Example 3

    We can likewise use the locals() and globals() dictionaries to assign values to variables in the expression that you are evaluating. Here is an example:

    # Python program for eval() function  
    
    x = 20  
    
    y = 30  
    
    expr = 'x + y + z'  
    
    result = eval(expr, globals(), {'z': 50})  
    
    print(result)

    Output:

    100
    

    Explanation:

    In this example, we have defined two variables x and y, a string expr that contains a Python expression, and a dictionary reference that contains the worth of the variable z. We then, at that point, call the eval() function with the globals() and locals() functions as contentions. The eval() function evaluates the expression ‘x + y + z’ utilizing the globals() and locals() namespaces and returns the outcome, which is 100.

    Utilizing locals() and globals() with the eval() function can be useful when you want to evaluate an expression in a particular context, like a function or class. Be that as it may, it means quite a bit to use these contentions with caution, as they can permit us to change variables unexpectedly.

    Conclusion

    The eval() function is an amazing asset in Python that permits us to execute dynamically produced code and perform complex numerical computations. In many cases, it is best to use the eval() function with caution and know about its possible security, execution, and maintenance issues.

  • Python bytearray() Function

    The python bytearray() function returns a bytearray object and can convert objects into bytearray objects, or create an empty bytearray object of the specified size.

    Python bytearray() Function Syntax

    It has the following syntax:

    bytearray(x, encoding, error)  

    Parameters

    • x (optional): It is the source that initializes the array of bytes.
    • encoding (optional): It is an encoding of the string.
    • error (optional): It takes action when the encoding fails.

    Return

    It returns an array of bytes.

    Different Examples for Python bytearray() Function

    Here, we are going to discuss several examples for Python bytearray() Function.

    Python bytearray() Function Example 1

    The below example shows an array of bytes from a string:

    string = "Python is programming language."  
    
      
    
    # string with encoding 'utf-8'  
    
    arr = bytearray(string, 'utf-8')  
    
    print(arr)

    Output:

    bytearray(b'Python is programming language.')
    

    Explanation: In the above example, we take a variable that contains a string value and convert it into a bytearray object.

    Python bytearray() Function Example 2

    The below example shows an array of bytes of given integer size:

    size = 5  
    
      
    
    arr = bytearray(size)  
    
    print(arr)

    Output:

    bytearray(b'\x00\x00\x00\x00\x00')
    

    Python bytearray() Function Example 3

    The below example shows an array of bytes from an iterable list:

    rList = [2, 3, 4, 5, 6]  
    
      
    
    arr = bytearray(rList)  
    
    print(arr)

    Output:

    bytearray(b'\x02\x03\x04\x05\x06')
  • Python ascii() Function

    The python ascii() function returns a string containing a printable representation of an object and escapes the non-ASCII characters in the string using \x, \u or \U escapes.

    Python ascii() Function Syntax

    Let us take an example to demonstrate the ascii() function in Python.

    ascii(object)  

    Parameters

    object: It takes an object like strings, list etc.

    Return

    It returns a readable version of an object and replaces none-ascii characters with the escape character.

    Python ascii() Function Example

    Here, we are going to discuss different examples for Python ascii() Function works in Python.

    normalText = 'Python is interesting'  
    
    print(ascii(normalText))  
    
      
    
    otherText = 'Pyth�n is interesting'  
    
    print(ascii(otherText))  
    
      
    
    print('Pyth\xf6n is interesting')

    Output:

    'Python is interesting'
    'Pyth\xf6n is interesting'
    Pyth�n is interesting
    

    Explanation: In the above example, variables such as normalText, and otherText contain the string values, and returns ascii value of a particular variable.