Modules

Introduction To Python
  1. Advantages Of Learning Python As The First Programming Language
  2. Easy Python Setup Guide For Beginners
Basic Syntax And Variables
  1. Python Syntax Fundamentals
  2. Python Variables And Data Types
  3. Python Basic Operations
Control Flow
  1. Python Conditional Statements
  2. Python Loops
Functions And Modules
  1. Defining And Calling Python Functions
  2. Introduction To Python Modules And Importing
  3. Understanding Python Built In Functions Part 1
  4. Understanding Python Built In Functions Part 2
  5. Understanding Python Built In Functions Part 4
  6. Understanding Python Lambda Functions
Python Lists And Touples
  1. Manipulate Python Lists And Touples
  2. 5 Ways To Remove Items From A Python List By Index
  3. 5 Different Approaches To Check For Duplicate Values In Python Lists
  4. 5 Different Approaches To Check For A Specific Value In Python Lists
  5. 5 Various Approaches To Modify Elements In Python Lists
  6. Understanding Shallow Copy And Deep Copy In Python Lists
  7. 6 Various Approaches To Duplicating Lists In Python
  8. Exploring 8 Various Iteration Techniques In Python Lists
  9. Exploring Python List Concatenation Methods
  10. All You Must Know About Python Slicing
  11. Exploring Various Methods For Comparing Python Lists
  12. Converting Various Data Types To Python Lists
  13. Removing Duplicate Values From Python Lists
  14. Extend A Python List To A Desired Length
  15. Shorten A Python List To A Specific Length
  16. Efficient Ways To Creating Sequences In Python
Python Dictionaries
  1. Manipulate Python Dictionaries
  2. Understanding Python Enumerate Dictionary
  3. Efficient Ways Removing Items From Python Dictionaries
  4. 5 Different Ways To Check For Duplicate Values In Python Dictionaries
  5. Check For A Specific Value In Python Dictionaries
  6. Get Values By Key In Python Nested Dictionary
  7. Modify Values By Key In Python Nested Dictionary
  8. 7 Different Ways To Duplicating A Dictionary In Python
  9. 5 Various Iteration Techniques In Python Dict
  10. 4 Different Methods For Dictionary Concatenation In Python
  11. 4 Different Ways Of Comparing Python Dicts
  12. Converting Various Data Types To Python Dictionaries
  13. Efficient Ways To Remove Duplicate Values From Python Dictionaries
  14. Extend A Python Dictionary To A Desired Length
  15. Shorten Python Dictionaries To A Specific Length
  16. Efficient Approaches To Remove An Item By Value In Python Dictionaries
Python Sets
  1. Manipulate Python Sets
File Handling
  1. Reading From And Writing To Files In Python
  2. Python File Modes And Handling Exceptions
Object Oriented Programming
  1. Python Classes And Objects
  2. Python Inheritance Encapsulation And Polymorphism
Python Advanced Data Structures
  1. Python Collection Module
  2. Advanced Python Data Manipulation Techniques
Error Handling And Debugging
  1. Python Exception Handling
  2. Python Debugging Techniques And Tools
Regular Expressions
  1. Python Regular Expressions In Text Processing
  2. Python Regular Expressions Pattern Matching
Concurrency And Parallelism
  1. Threading Vs Multiprocessing In Python
  2. How To Achieve Concurrency And Parallelism In Python
  3. Concurrent Programming With Asyncio
Working With Apis
  1. Making Http Requests In Python
  2. Parsing Json Xml Responses In Python
Build Apis With Python Requests
  1. Python Requests Crud Operations
  2. Retry In Python Requests
  3. Python Requests Timeout
Build Apis With Python Urllib3
  1. Disabling Hostname Verification In Python Example
Build Apis With Python Aiohttp
  1. Asynchronous Crud Operations In Python
  2. Retry In Python Aiohttp Async Requests
Database Interaction
  1. Connecting To Databases In Python
  2. Python Crud Operations And Orm Libraries
Python For Web Development
  1. Introduction To Python Web Frameworks
  2. Building Web Applications Using Flask
  3. Building Web Applications Using Django
  4. Building Web Applications Using Fastapi
Data Analysis And Visualization
  1. Introduction To Numpy Pandas And Matplotlib
  2. Analyzing Datasets And Visualizations In Python
Machine Learning With Python
  1. Machine Learning Concepts And Python
  2. Introduction To Scikit Learn And Tensorflow Keras
Python Typing Module
  1. Type Error Not Subscriptable While Using Typing
All Course > Python > Functions And Modules Oct 12, 2023

Understanding Python Built-in Functions Part 3

Python has a rich set of built-in functions that can be used for various programming needs. In this article, we'll dive into each of these functions from M to R, providing examples and insights into their usage.

This is the part 3 of the Python built-in function tutorial series and will cover following built-in functions. Checkout the these links for other python built-in function tutorials.

map() function

The map() function applies a specified function to each item of one or more iterable arguments, returning an iterator over the results. The function takes two arguments: the first is the function to apply, and the subsequent arguments are the iterables whose elements will be processed by the function.

map() function efficiently processes corresponding elements from the provided iterables, producing a new iterable with the outcomes of the applied function. This function is particularly useful for scenarios where you need to perform the same operation on every element of one or more iterables, allowing for concise and expressive code.

def square(x):
    return x ** 2

numbers = [1, 2, 3, 4]
squared_numbers = list(map(square, numbers))
print(squared_numbers)  # Output: [1, 4, 9, 16]

max() function

The max() function returns the highest value from a sequence or a set of arguments. It can take an iterable, a series of values, or multiple arguments and returns the maximum element based on their natural order or a specified key function. When applied to non-numeric types, max() function determines the maximum value based on lexicographical order.

This function is widely used for finding the largest element in a collection, facilitating tasks such as identifying the maximum value in a list or determining the maximum key in a dictionary.

numbers = [3, 7, 1, 9, 4]
maximum_number = max(numbers)
print(maximum_number)  # Output: 9

memoryview() function

The memoryview() function is used for creating a memory view object from an object that supports the buffer protocol, such as a bytes or bytearray object. This function provides a way to expose the internal data of a mutable sequence without making a copy, offering an efficient and memory-friendly approach to working with large datasets. The resulting memory view object allows for viewing and manipulating the underlying data in a memory-efficient manner.

Developers commonly use memoryview() function in scenarios where direct access to the raw bytes of an object is required, particularly when dealing with binary data or memory-intensive operations.

byte_array = bytearray(b'Hello, World!')
view = memoryview(byte_array)
print(view[0])  # Output: 72 (ASCII code for 'H')

min() function

The min() function returns the smallest value from a sequence or a set of arguments. It can take an iterable, a series of values, or multiple arguments and returns the minimum element based on their natural order or a specified key function. When applied to non-numeric types, min() function determines the minimum value based on lexicographical order.

This function is commonly used for finding the smallest element in a collection, facilitating tasks such as identifying the minimum value in a list or determining the minimum key in a dictionary.

numbers = [3, 7, 1, 9, 4]
minimum_number = min(numbers)
print(minimum_number)  # Output: 1

next() function

This function is used to retrieve the next item from an iterator object. It takes two arguments—the iterator and an optional default value—and returns the next element in the iterator. If the iterator is exhausted and no default value is provided, it raises the StopIteration exception.

This function is commonly used in loops or scenarios where sequential access to elements is required. Developers often leverage next() function to iterate through elements, especially when working with custom iterators or handling cases where a default value can gracefully handle exhaustion.

my_iter = iter([1, 2, 3])
next_item = next(my_iter)
print(next_item)  # Output: 1

object() function

The object() function is returns a new featureless object. This object serves as a base for all other classes and instances in the Python language. While object() function doesn’t have any methods or attributes of its own, it plays a crucial role in the object-oriented paradigm as the root of the inheritance hierarchy. Essentially, all Python classes are subclasses of the object class.

Developers may use object() function when they need a simple and generic object without specific functionalities, or as a reference point for creating more complex class hierarchies. While the direct use of object() function may be limited in everyday programming, its significance lies in its foundational role in the Python class hierarchy, contributing to the principles of object-oriented programming within the language.

empty_object = object()
print(empty_object)  # Output: <object object at 0x...>

oct() function

The oct() function is used to convert an integer to its octal (base-8) representation. It takes an integer as its argument and returns a string representing the octal equivalent of that integer. The resulting string is prefixed with ‘0o’ to signify its octal nature.

This function is often utilized in scenarios where a human-readable representation of an integer in octal (base-8) is required, such as when dealing with permissions, file modes, or other situations where octal notation is relevant.

decimal_number = 16
octal_representation = oct(decimal_number)
print(octal_representation)  # Output: '0o20'

open() function

The open() function is used for opening files and returning a file object. It is a fundamental tool for file I/O operations in Python. The function takes two arguments, the file name and the mode in which the file should be opened (e.g., ‘r’ for read, ‘w’ for write, or ‘a’ for append). Optionally, it can also take additional arguments like encoding and buffering parameters.

The open() function function allows Python programs to interact with external files, read their contents, write new data, or modify existing content. It supports a variety of file types, and developers commonly use it in conjunction with other file-related operations, such as reading lines, writing data, or seeking within the file. Properly closing the file using the close() method of the file object is crucial after performing the necessary operations to ensure proper resource management.

file_path = 'example.txt'
with open(file_path, 'r') as file:
    content = file.read()
    print(content)

ord() function

The ord() function is a built-in function that returns the Unicode code point of a given character. It takes a single character as its argument and returns an integer representing the Unicode code point of that character.

This function is particularly useful when dealing with character encoding and processing individual characters within strings. For example, ord('A') would return 65, as 65 is the Unicode code point for the uppercase letter ‘A’.

unicode_char = 'A'
unicode_value = ord(unicode_char)
print(unicode_value)  # Output: 65

pow() function

The pow() function is used for exponentiation. It takes two or three arguments: the base, the exponent, and an optional modulus. When provided with two arguments, it returns the result of raising the base to the power of the exponent. If a third argument is supplied, the function calculates the result modulo the specified modulus.

The pow() function function provides a convenient and efficient way to perform exponentiation operations in Python, whether for simple mathematical calculations or more complex computations.

result = pow(2, 3)
print(result)  # Output: 8

The print() function is a built-in function used for outputting information to the console or a file. It takes one or more arguments, which can be strings, variables, or expressions, and displays them to the standard output by default. The print() function is a fundamental tool for displaying messages, variables, or any other content during program execution, aiding in debugging, logging, and user interaction.

It supports various formatting options and can be customized to control the appearance of output. While primarily used for printing to the console, the print() function can also be redirected to write output to a file by specifying a file parameter. In Python 3, print() is a function, whereas in Python 2, it was a statement.

print("Hello, World!")

property() function

The property() function facilitates the creation of properties within a class. It allows developers to define getter, setter, and deleter methods for managing the access, modification, and deletion of an object’s attributes. When used as a decorator or in combination with the property attribute, property() function transforms these methods into attributes that can be accessed, assigned, and deleted like regular attributes, providing a more controlled and intuitive interface for class properties.

The property() function is particularly useful for implementing data encapsulation and managing attribute access in a way that allows for additional logic or validation during these operations. This function contributes to the creation of clean and maintainable object-oriented code in Python, enhancing the flexibility and readability of class designs.

class Example:
    def __init__(self):
        self._x = 0

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

obj = Example()
print(obj.x)  # Output: 0
obj.x = 42
print(obj.x)  # Output: 42

range() function

The range() function generates a sequence of numbers within a given range. It takes up to three arguments, the start value, the end value (exclusive), and an optional step value. When used with a single argument, range() function creates a sequence from 0 to the specified end value. With two arguments, it generates a sequence starting from the first argument to the second (exclusive). The step value, if provided, determines the spacing between numbers in the sequence.

range() function is commonly used in for loops to iterate over a sequence of numbers. It is a memory-efficient tool, particularly useful when dealing with large ranges, as it generates values on-the-fly without precomputing the entire sequence.

for i in range(5):
    print(i)

Result:

0
1
2
3
4

repr() function

The repr() function returns a string representation of an object. Unlike the str() function, which is focused on creating a readable representation of an object for end-users, repr() function is designed to produce a string that, when passed to the eval() function, could recreate the original object. It provides a more unambiguous and detailed view of an object’s internal state, making it particularly useful for debugging and development purposes.

Developers often implement a special method called __repr__() within their classes to define the representation produced by repr() function for instances of that class.

string_representation = repr(42)
print(string_representation)

Result:

'42'

reversed() function

The reversed() function returns a reversed iterator of a specified iterable. It takes an iterable object as its argument, such as a list or a string, and produces an iterator that traverses the elements of the iterable in reverse order. While reversed() function itself returns an iterator, it is commonly used with the list() function to create a reversed list.

This function is particularly useful when one needs to iterate over elements in a backward direction without modifying the original iterable.

reversed_list = list(reversed([1, 2, 3]))
print(reversed_list)

Result:

[3, 2, 1]

round() function

The round() function is used for rounding numerical values to a specified number of decimal places. It takes one or two arguments, the first is the number to be rounded, and the second (optional) argument specifies the number of decimal places. If the second argument is omitted, the function rounds the number to the nearest integer. When a second argument is provided, round() function performs decimal rounding, rounding the number to the specified number of decimal places.

This function is commonly used in situations where precision needs to be controlled, such as when dealing with financial calculations, display formatting, or any context where a specific level of precision is desired.

rounded_number = round(3.14159, 2)
print(rounded_number)

Result:

3.14

Conclusion

Python’s built-in functions offer a wide array of capabilities, simplifying common programming tasks. Understanding these functions enhances your proficiency as a Python developer, allowing you to write more efficient and concise code. In this comprehensive guide, we’ve explored essential Python functions from M to R. Incorporating these functions into your Python code will undoubtedly enhance your programming experience.

Comments

There are no comments yet.

Write a comment

You can use the Markdown syntax to format your comment.

Tags: python built-in functions