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

Understanding Python Built-in Functions Part 2

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 F to L, providing examples and insights into their usage.

This is the part 2 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.

filter() function

The filter() function provides a way to filter elements from an iterable based on a specified function or conditional expression. It takes two arguments—the filtering function and the iterable—and returns an iterator containing only the elements that satisfy the given condition. The filtering function should return True for the elements to be included in the result.

This function is commonly used for selectively extracting elements from lists, tuples, or other iterable objects, streamlining the process of data manipulation.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
# Output: [2, 4, 6, 8]

float() function

The float() function is used to convert a number or a string representing a floating-point number into an actual float data type. This function is versatile, as it can handle various input types, including integers, strings, or even other float values.

When applied to a string, float() function parses and converts the string to its corresponding floating-point representation.

num_str = "3.14"
num_float = float(num_str)
print(num_float)
# Output: 3.14

format() function

The format() function allows for the formatting of values within strings. It is commonly used to create formatted output by substituting placeholders with actual values. The method employs curly braces {} as placeholders in a string, and these are replaced with the specified arguments passed to the format() function.

name = "John"
age = 29
formatted_str = "My name is {} and I am {} years old.".format(name, age)
print(formatted_str)
# Output: My name is John and I am 29 years old.

frozenset() function

The frozenset() function creates an immutable and hashable frozenset object from an iterable. While similar to the set() function, which creates mutable sets, frozenset() function generates an unchangeable set-like object. Once created, a frozenset cannot be modified by methods like add or remove.

This is suitable for scenarios where an unalterable collection of unique elements is required. Frozensets can be used as keys in dictionaries or elements in other sets, unlike regular sets, which are not hashable and thus cannot be used in these contexts.

set1 = {1, 2, 3}
frozen_set = frozenset(set1)
print(frozen_set)
# Output: frozenset({1, 2, 3})

getattr() function

The getattr() function provides a dynamic way to access the attribute of an object. It takes three arguments, the object, the name of the attribute as a string, and an optional default value. If the specified attribute exists in the object, getattr() function returns its value. Itherwise, it returns the default value or raises an AttributeError if no default is provided.

This function is particularly useful when dealing with objects where the attribute names are determined at runtime or are subject to change.

class MyClass:
    x = 10

obj = MyClass()
value = getattr(obj, 'x')
print(value)
# Output: 10

globals() function

The globals() function returns a dict having the current global symbol table. This dictionary contains all global variables and their values in the current module or, if invoked at the top level of a script or program, the global variables of the entire script.

This function is often used globals() function to access or modify global variables dynamically during runtime. While modifying global variables directly is generally discouraged for clarity and maintainability reasons, globals() function provides a means to inspect and manipulate global symbols when necessary.

x = 10
y = 20
global_vars = globals()
print(global_vars)
# Output: {'x': 10, 'y': 20, ... (other global variables)}

hasattr() function

The hasattr() function is used to determine whether an object has a specific attribute or not. It takes two arguments—the object and the attribute name as a string—and returns True if the attribute exists, and False otherwise.

This function is used in scenarios where the availability of certain attributes in an object may vary, and they need to handle these variations gracefully.

class MyClass:
    x = 5

obj = MyClass()
has_x = hasattr(obj, 'x')
print(has_x)
# Output: True

hash() function

The hash() function returns the hash value of an object. The hash value is a numerical representation generated based on the object’s contents, and it is commonly used in hash tables and dictionary implementations for efficient data retrieval.

Objects that are considered hashable, such as strings or integers, produce unique hash values, ensuring that distinct objects have distinct hash codes.

hashed_value = hash("Hello, World!")
print(hashed_value)
# Output: -536808363803547653

help() function

The help() function launches the interactive help system. When called without arguments, it opens an interactive help session, allowing users to navigate and search for information about Python modules, classes, functions, and keywords. If provided with an object, module, or keyword as an argument, help() function displays information related to that specific entity.

This function serves as a valuable resource for providing detailed documentation and examples directly within the Python interpreter.

help(list)
# Output: (displays help documentation for the list type)

hex() function

The hex() function is used for converting an integer to its hexadecimal representation. It takes an integer as its argument and returns a string representing the hexadecimal equivalent of that integer. The resulting string is prefixed with ‘0x’ to indicate its hexadecimal nature.

This function is often employed in scenarios where a human-readable representation of an integer in base-16 is required, such as when dealing with memory addresses, bitwise operations, or other situations involving hexadecimal notation.

decimal_num = 255
hex_value = hex(decimal_num)
print(hex_value)
# Output: '0xff'

id() function

The id() function returns the identity of an object, which is a unique integer representing the object’s address in memory. This integer value remains constant for the lifetime of the object, making it a reliable way to identify and distinguish between different objects.

The id() function is particularly useful when comparing object instances or tracking the life cycle of objects during program execution. However, it’s important to note that the identity value itself doesn’t carry any meaningful information about the object’s contents or type—it simply serves as a unique marker for that specific instance.

x = 42
identity = id(x)
print(identity)
# Output: (some unique integer representing the identity of x)

input() function

The input() function allows the user to interactively provide input to a program. When called, it prompts the user with a message (specified as an argument) and waits for the user to enter text through the keyboard. The entered text is then returned as a string.

name = input("Enter your name: ")
print("Hello, " + name + "!")
# (User input required)

int() function

The int() function is used for converting a specified value to an integer. It can handle various input types, including strings, floats, and other numeric types, converting them to their corresponding integer representations. When applied to a string, int() function parses the string and converts it to an integer, assuming the string represents a valid integer literal.

Additionally, the function supports an optional second argument specifying the base for interpreting the string, allowing conversions from binary, octal, or hexadecimal representations.

num_str = "42"
num_int = int(num_str)
print(num_int)
# Output: 42

isinstance() function

The isinstance() function checks whether an object belongs to a specified class or a tuple of classes. It takes two arguments: the object to be checked and a class or a tuple of classes. If the object is an instance of any of the specified classes, the function returns True; otherwise, it returns False.

This function is particularly useful when dealing with polymorphism and ensuring that an object possesses the expected type before performing certain operations.

value = 42
is_int = isinstance(value, int)
print(is_int)
# Output: True

issubclass() function

The issubclass() function is designed to check whether a given class is a subclass of another class. It takes two arguments: a potential subclass and a potential superclass. If the first argument is indeed a subclass of the second, the function returns True; otherwise, it returns False.

This function is useful for verifying class relationships and hierarchies, providing a means to dynamically assess the inheritance structure of classes during program execution.

class Parent:
    pass

class Child(Parent):
    pass

is_sub = issubclass(Child, Parent)
print(is_sub)
# Output: True

iter() function

The iter() function is used for obtaining an iterator object from an iterable. It takes two arguments—the iterable and an optional sentinel value—and returns an iterator that can be used to traverse the elements of the iterable sequentially. If a sentinel value is provided, the iterator will continue until it encounters the sentinel, allowing for more dynamic control over iteration.

This function is commonly utilized in situations where manual iteration over elements is required.

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

len() function

The len() function is used to determine the length of an object, typically an iterable like a list, tuple, or string. When applied to a sequence or collection, len() function returns the number of elements or characters it contains.

This function is fundamental in obtaining information about the size or dimensionality of data structures, aiding in tasks like loop control, indexing, and general program logic.

my_list = [1, 2, 3, 4, 5]
length_of_list = len(my_list)
print(length_of_list)  # Output: 5

list() function

The list() function is used for creating a new list or converting an iterable object, such as a tuple or string, into a list. When called with no arguments, it returns an empty list.

This function serves as a versatile tool for list creation and manipulation, providing a convenient way to transform data structures into lists or initialize lists with specific values.

new_list = list(range(1, 4))
print(new_list)  # Output: [1, 2, 3]

locals() function

This function returns a dict containing the current local symbol table. This dictionary holds information about the local variables in the current scope, including their names and values. While similar to the globals() function, which provides information about global variables, locals() function specifically focuses on the local variables within a function or code block.

Developers often use locals() function when they need to introspect or manipulate local variables dynamically. However, it’s important to note that modifications to the dictionary returned by locals() function do not affect the actual local variables in the program.

def example_function():
    x = 10
    local_symbols = locals()
    print(local_symbols)

example_function()
# Output: {'x': 10}

Conclusion

Python’s built-in functions offer a wide range 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 built-in functions from F to L. 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