All Course > Python > Functions And Modules Oct 10, 2023

Understanding Python Built-in Functions Part 1

Python built-in functions are sort of tools for making computer programs better. It has many buit-in functions. Each function does some thing special. We're going to look at some of those function, beginning from A to E. I'll show you what they do with examples.

This is part 1 of the Python built-in function article series and here, will cover the following built-in functions. Checkout the these links for other python built-in function.

abs function

Python’s abs() function returns the absolute value of a number. It takes one argument, which is the number whose absolute value is desired. For instance, if you pass -5 to abs(), it will return 5. It doesn’t matter if the number is positive or negative; abs() will always return the positive value. This function is handy when you need to work with distances, magnitudes, or simply want to ignore the sign of a number.

For example, when calculating differences between values or distances, the abs() function ensures that the result is consistently positive.

abs_value = abs(-5)
print(abs_value)  # Output: 5

all() function

The all() function function in Python checks if all elements in a list are True. It returns True if they are, and False if any element is False. You can use it with lists containing any data type. For example, you can use it to verify if all numbers in a list are positive. If you have a list of boolean values, you can check if they’re all True. It’s useful for tasks like filtering data or validating user inputs.

all_true = all([True, True, True])
print(all_true)  # Output: True

any() function

The Python any() function function checks if any element in a given iterable is true. It returns True if any element is true and False otherwise. For example, you can use it to see if there are any even numbers in a list. The function iterates over each element in the iterable and stops at the first one that evaluates to true. If it finds one, it returns True; otherwise, it returns False. This function is helpful when you need to determine whether there’s at least one element in a collection that meets a certain condition.

any_true = any([False, True, False])
print(any_true)  # Output: True

bin() function

bin() function takes one argument, which is an integer. This function returns a binary representation of the integer passed to it. For example, bin(5) returns the string ‘0b101’, where ‘0b’ indicates that the string is in binary format and ‘101’ is the binary representation of the decimal number 5. This function is useful for tasks that involve binary operations or when you need to represent integers in binary format.

binary_str = bin(10)
print(binary_str)  # Output: '0b1010'

bool() function

The bool() function converts a value to its boolean representation. When applied, the bool() function evaluates the truthiness of the given value, returning either True or False.

For instance, when dealing with conditional statements or logical operations, the bool() function can help clarify the boolean value of a particular condition.

The bool() function is a built-in function in Python which converts a value to a Boolean, returns either True or False. The function takes a single argument and checks the truthiness of the given value. Values such as 0, None, False, empty lists, and empty strings, which are considered falsey, return False. Other values, which are considered truthy, return True. The bool() function is helpful in making code more readable.

bool_value = bool(1)
print(bool_value)  # Output: True

ascii() function

ascii() function is used to create a string representation of an object. When applied to an object, the ascii() function returns a string containing a printable version of the object.

This function is particularly useful when you want to obtain a string representation of an object that includes escape sequences for non-printable or special characters.

ascii_str = ascii("hello, world!")
print(ascii_str)  # Output: 'hello, world!'

bytearray() function

The bytearray() function takes various types of input, such as integers, strings, or other iterable objects, and convert them into a bytearray object. The resulting bytearray can be modified, unlike immutable bytes objects.

This function is useful in situations where a mutable representation of binary data is required, allowing for in-place modifications.

byte_array = bytearray([65, 66, 67])
print(byte_array)  # Output: bytearray(b'ABC')

bytes() function

The bytes() function creates an immutable sequence of bytes. It takes an iterable of integers as its argument, converting each integer to a byte and then constructing a bytes object from those bytes.

This function is commonly used to represent binary data in a way that cannot be modified after creation. It is particularly useful in scenarios where a fixed and unalterable sequence of bytes is required, such as when dealing with binary file formats or network protocols.

bytes_obj = bytes([65, 66, 67])
print(bytes_obj)  # Output: b'ABC'

callable() function

The callable() function allows you to check whether an object is callable, i.e., whether it can be called as a function. When applied to an object, callable() returns True if the object appears callable (can be invoked with parentheses), and False otherwise.

This function is useful for dynamically determining if a given object, such as a function or a class instance, can be invoked like a function. It helps in making runtime decisions in your code, ensuring that you are working with callable entities before attempting to call them.

is_callable = callable(print)
print(is_callable)  # Output: True

chr() function

The chr() function takes an integer representing a Unicode code point and returns the corresponding character. Essentially, it converts a numeric Unicode code point into its corresponding Unicode character.

For example, chr(65) would yield the character ‘A’, as 65 is the Unicode code point for the uppercase letter ‘A’.

char = chr(65)
print(char)  # Output: 'A'

compile() function

The compile() function transforms a source code string into a code object, which can then be executed or evaluated by the Python interpreter. The resulting code object can be executed using the exec() function or evaluated with eval() function.

The compile() function is beneficial in situations where dynamic generation or manipulation of Python code is required at runtime. It is commonly used in scenarios such as code generation, interpreter development, and dynamic execution of Python code within a program.

compiled_code = compile("print('Hello, World!')", "", "exec")
exec(compiled_code)  # Output: Hello, World!

complex() function

The complex() function is used to create a complex number from either real and imaginary parts or from a single numerical value. Complex numbers are essential in mathematical and scientific computations, especially in fields like engineering and physics.

The complex() function facilitates the creation and manipulation of complex numbers in a straightforward manner.

complex_num = complex(1, 2)
print(complex_num)  # Output: (1+2j)

delattr() function

The delattr() function is used to delete an attribute from an object. This function provides a dynamic way to manage an object’s attributes during runtime.

It is particularly useful when you need to modify or clean up an object’s structure by removing certain attributes dynamically.

class Example:
    x = 10

obj = Example()
delattr(obj, '`x')
# Now obj.x will raise an AttributeError

dict() function

The dict() function is used to create a new dictionary or convert an iterable of key-value pairs into a dictionary. When no arguments are provided, it returns an empty dictionary.

The dict() function provides a convenient and concise way to work with data organization and manipulation in Python programs.

new_dict = dict(a=1, b=2, c=3)
print(new_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}

dir() function

The dir() function returns a sorted list of names in the current local scope or the attributes of a specified object. When invoked without arguments, it provides a list of names in the current scope, including variables, functions, and modules. If an object is passed as an argument, dir() returns a list of attributes and methods associated with that object.

This function is valuable for exploring the contents of a module, class, or any Python object. It is often used during development and debugging to examine the structure and capabilities of objects.

dir_list = dir()
print(dir_list)

divmod() function

The divmod() function takes two arguments and returns a tuple containing the quotient and the remainder of the division operation. The first argument represents the dividend, and the second argument is the divisor.

The result is a tuple (a, b), where a is the quotient obtained by performing the floor division of the two numbers, and b is the remainder.

This function is particularly useful in scenarios where both the result of the division and the remainder are needed simultaneously.

divmod_result = divmod(10, 3)
print(divmod_result)  # Output: (3, 1)

enumerate() function

The enumerate() function is commonly used when iterating over sequences like lists, tuples, or strings. It takes an iterable as its argument and returns an iterator that produces tuples containing the index and corresponding element of the iterable.

This function is particularly useful in scenarios where both the index and the value of elements in a sequence are needed during iteration.

fruits = ['apple', 'banana', 'cherry']
enumerated_fruits = list(enumerate(fruits, start=1))
print(enumerated_fruits)
# Output: [(1, 'apple'), (2, 'banana'), (3, 'cherry')]

eval() function

The eval() function allows the dynamic execution of Python expressions or statements represented as strings. It takes a string as its argument and evaluates it as a Python expression, returning the result.

This function is particularly useful in situations where code needs to be generated or executed dynamically during runtime. However, it should be used with caution as it poses security risks, especially if the input string is obtained from untrusted sources, as it can execute arbitrary code.

x = 5
y = 10
result = eval('x + y')
print(result)
# Output: 15

exec() function

The exec() function dynamically executes Python code represented as a string. It takes either a string containing a block of code or a code object as its argument and runs the code within the current Python environment. Similar to the eval() function, exec() allows for the dynamic generation and execution of code during runtime. However, exec() is designed for executing multiple statements or larger code blocks, whereas eval() is generally used for evaluating single expressions.

While exec() provides flexibility for certain advanced programming scenarios, it should be used judiciously due to potential security risks, especially when handling code from untrusted sources.

code = '''
for i in range(5):
    print(i)
'''
exec(code)
# Output:
# 0
# 1
# 2
# 3
# 4

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 across different categories. 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