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.
- Python Built-in Functions Part 1(A-E)
- Python Built-in Functions Part 2(F-L)
- Python Built-in Functions Part 4(S-Z)
M | N | O | P | R |
---|---|---|---|---|
map() | next() | object() | pow() | range() |
max() | oct() | print() | repr() | |
memoryview() | open() | property() | reversed() | |
min() | ord() | round() |
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
print()
function
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.