Table of Contents
The Python built-in -functions are referred to as the functions where the functionality is pre-defined in Python. Whereas, the Python interpreter consists of several functions that will be available for use. So, these functions are known as Python Built-in Functions. Let us check out this article to learn more about Python Built-in Functions.
What is Python abs() Function?
The Python abs() function will return the value of a number. Thus, it will take only one argument, a number where the value will be returned. This argument can either be an integer or a floating-point number. Suppose, if the argument is a complex number, thus, abs() will return their magnitude.
Example
# Example using abs() function
number = -10
absolute_value = abs(number)
# Output
print(f"The absolute value of {number} is: {absolute_value}")
Output
The absolute value of -10 is: 10
What is Python all() Function?
The Python all() function will accept the iterable object that includes list, and dictionary. Hence, it will return all items when the iterable is true. But, if it comes false. So, the iterable object will become empty and all() functions will be true.
Example
# Example using all() function
numbers = [2, 4, 6, 8, 10]
# Check if all numbers are even
are_all_even = all(num % 2 == 0 for num in numbers)
# Output
print(f"Are all numbers even? {are_all_even}")
Output
Are all numbers even? True
What is the Python bin() Function?
The Python bin() function will operate to return the binary representation of a specified integer. So, the output will begin with the prefix Ob.
Example
# Example using bin() function
decimal_number = 10
# Convert decimal_number to binary
binary_representation = bin(decimal_number)
# Output
print(f"The binary representation of {decimal_number} is: {binary_representation}")
Output
The binary representation of 10 is: 0b1010
What is Python Bool()
Python bool() will function to convert the value into a boolean such as True or False with the standard truth testing procedure.
Example
# Example using bool() function
value_1 = 42
value_2 = 0
# Convert values to boolean
bool_value_1 = bool(value_1)
bool_value_2 = bool(value_2)
# Output
print(f"Boolean value of {value_1}: {bool_value_1}")
print(f"Boolean value of {value_2}: {bool_value_2}")
Output
Boolean value of 42: True
Boolean value of 0: False
What is Python bytes()?
The Python bytes() work to return the bytes object. It is considered an immutable version of the byte array() function. Thus, it can make the empty bytes object in the required size.
Example
# Example using bytes() function
byte_values = [65, 66, 67, 68] # ASCII values for 'A', 'B', 'C', 'D'
# Create a bytes object from list of integers
byte_sequence = bytes(byte_values)
# Output
print(f"Bytes object: {byte_sequence}")
Output
Bytes object: b'ABCD'
What is the Python callable () Function?
This Python callable () method will take only one argument, an object, and then return one of the two values. Whereas, if the output is true then the object will become callable.
# Example using callable() function with x = 4
def example_function():
print("Hello, from the example function!")
class ExampleClass:
def __call__(self):
print("Hello, from the __call__ method of ExampleClass!")
# Create an instance of ExampleClass
example_instance = ExampleClass()
# Check if objects are callable
x = 4 # Setting x to 4
is_function_callable = callable(example_function)
is_instance_callable = callable(example_instance)
# Output
print(f"Is example_function callable with x = {x}? {is_function_callable}")
print(f"Is example_instance callable with x = {x}? {is_instance_callable}")
Output
Is example_function callable with x = 4? True
Is example_instance callable with x = 4? True
What is the Python compile() Function?
The Python compile () function will use the source code as the input and then return the code object. Then, it will be run by the exec() function.
Example
# Example using compile() function with x = 4
x = 4
source_code = f"result = x * 2; print('Result:', result)"
# Compile the source code
compiled_code = compile(source_code, filename="<string>", mode="exec")
# Execute the compiled code
exec(compiled_code)
Output
Result: 8
What is the Python exec() Function?
The Python exec () will work for the dynamic execution of the Python program and will be either a string or an object. Thus, it will accept large blocks of code .
Example
# Example using exec() function
python_code = """
x = 4
result = x * 3
print(f"The result of x * 3 is: {result}")
"""
# Execute the Python code
exec(python_code)
Output
The result of x * 3 is: 12
What is the Python sum() Function?
In Python sum() function will enable us to add all the numbers in the list.
Example
# Example using sum() function
numbers = [1, 2, 3, 4, 5]
# Calculate the sum of numbers in the list
result_sum = sum(numbers)
# Output
print(f"The sum of numbers in the list is: {result_sum}")
Output
The sum of numbers in the list is: 15
What is Python any() Function?
The Python any() Function will give the output as true if either the iterable comes true. In other cases, it will come False.
Example
# Example using any() function with I as 2, 4, 8
I = [2, 4, 8]
# Check if any value in the list is true
is_any_true = any(I)
# Output
print(f"Is there any true value in the list? {is_any_true}")
Output
Is there any true value in the list? True
What is Python ASCII () Function?
The Python ASCII () function will return the string and has the printable representation of the object. However, it will ignore the non-ASCII characters in the string with the \x, \u, or \U escapes.
# Example using ascii() function
character = '€'
# Get the ASCII representation of the character
ascii_representation = ascii(character)
# Output
print(f"The ASCII representation of '{character}' is: {ascii_representation}")
Output
The ASCII representation of '€' is: '\u20ac'
What is Python byte array()?
The Python byte array() will return the byte array output and then turn the objects into the byte array objects.
Example
# Example using bytearray() function
string_data = "Hello, Bytearray!"
# Convert a string to a bytearray
byte_array_data = bytearray(string_data, 'utf-8')
# Output
print(f"The original string: {string_data}")
print(f"The bytearray representation: {byte_array_data}")
Output
The original string: Hello, Bytearray!
The bytearray representation: bytearray(b'Hello, Bytearray!')
What is Python eval() Function?
The Python eval() function will rephrase the expression that is passed on to it and then it will execute the Python code in the Program
Example
# Example using eval() function
expression = "2 + 3 * 4"
# Evaluate the expression using eval()
result = eval(expression)
# Output
print(f"The result of the expression '{expression}' is: {result}")
Output
The result of the expression '2 + 3 * 4' is: 14
What is Python float()?
The Python float() function will return the floating-point number from a number or string.
Example
# Example using float() function
number_str = "7.5"
# Convert the string to a float
float_value = float(number_str)
# Output
print(f"The float representation of '{number_str}' is: {float_value}")
Output
The float representation of '7.5' is: 7.5
What is Python Format() Function?
The Python Format () function will help us to return the formatted representation of the provided value.
Example
# Example using format() function
name = "Alice"
age = 25
# Format a string with variables
formatted_string = "My name is {} and I am {} years old.".format(name, age)
# Output
print(formatted_string)
Output
My name is Alice and I am 25 years old.
What is Python Frozenset()?
The Python frozenset() function will allow us to return the immutable frozen set object that will be initialized with the elements from the given iterable.
Example
# Example using frozenset() function
set_values = {1, 2, 3, 4, 5}
# Create a frozenset from a set
frozen_set = frozenset(set_values)
# Output
print(f"The original set: {set_values}")
print(f"The frozenset representation: {frozen_set}")
Output
The original set: {1, 2, 3, 4, 5}
The frozenset representation: frozenset({1, 2, 3, 4, 5})
What is the Python getattr() Function?
The Python getattr() will return the value of the named attribute of an object. Hence, if it is not found, then it will return with the default value.
Example
# Example using getattr() function
class MyClass:
age = 25
# Create an instance of MyClass
obj = MyClass()
# Use getattr() to get the value of the 'age' attribute
attribute_value = getattr(obj, 'age', 'default_value')
# Output
print(f"The value of 'age' attribute is: {attribute_value}")
Output
The value of 'age' attribute is: 25
What is the Python global() Function?
The Python globals() function will operate to return the dictionary of the current global symbol table. The symbol table will be defined as the data structure, and have the required information regarding the program. Thus, it will have the variable names, methods, and classes.
Example
# Example using globals() function
global_variable = "I am a global variable"
def print_global_variable():
# Access global variable using globals()
global_variable_value = globals()['global_variable']
print(f"Inside the function: {global_variable_value}")
# Call the function
print_global_variable()
# Access global variable directly
direct_global_variable = globals()['global_variable']
print(f"Outside the function: {direct_global_variable}")
Output
Inside the function: I am a global variable
Outside the function: I am a global variable
What is Python hasattr() Function?
This function will return the true value only if any of the items is true, otherwise it will be false.
Example
# Example using hasattr() function
class MyClass:
name = "John"
age = 25
# Create an instance of MyClass
obj = MyClass()
# Check if the attribute 'name' exists in the object
has_name_attribute = hasattr(obj, 'name')
has_height_attribute = hasattr(obj, 'height')
# Output
print(f"Does the object have 'name' attribute? {has_name_attribute}")
print(f"Does the object have 'height' attribute? {has_height_attribute}")
Output
Does the object have 'name' attribute? True
Does the object have 'height' attribute? False
Python iter() Function?
The Python iter() Function will work to return the iterator object. Thus, it will make the object to /iterate one element at a time.
Example
# Example using iter() function
numbers = [1, 2, 3, 4, 5]
# Create an iterator object from the list
iterator = iter(numbers)
# Output
print("Using iterator to iterate through the list:")
for num in iterator:
print(num)
Output
Using iterator to iterate through the list:
1
2
3
4
5
What is the Python len() Function?
The Python len() function will work to return the length of the object.
Example
# Example using len() function
string_example = "Hello, Python!"
list_example = [1, 2, 3, 4, 5]
# Get the length of the string
string_length = len(string_example)
# Get the length of the list
list_length = len(list_example)
# Output
print(f"The length of the string is: {string_length}")
print(f"The length of the list is: {list_length}")
Output
The length of the string is: 13
The length of the list is: 5
What is Python list() ?
The Python list() will make a list in Python.
# Example using list() function
string_example = "Python"
tuple_example = (1, 2, 3, 4, 5)
# Convert a string to a list
string_as_list = list(string_example)
# Convert a tuple to a list
tuple_as_list = list(tuple_example)
# Output
print(f"Original string: {string_example}")
print(f"String as a list: {string_as_list}")
print(f"\nOriginal tuple: {tuple_example}")
print(f"Tuple as a list: {tuple_as_list}")
Output
Original string: Python
String as a list: ['P', 'y', 't', 'h', 'o', 'n']
Original tuple: (1, 2, 3, 4, 5)
Tuple as a list: [1, 2, 3, 4, 5]
What is Python local() Function?
The Python local() method will contain the update and then will return with the dictionary of the current local symbol table.
The symbol table is referred to as a data structure with the necessary information about the program. Additionally, it has variable names, methods, and classes.
Example
# Example demonstrating local variables and functions
def outer_function():
outer_variable = "I am a local variable"
def inner_function():
inner_variable = "I am also a local variable"
print(f"Inside inner_function: {inner_variable}")
print(f"Inside inner_function accessing outer_variable: {outer_variable}")
inner_function()
# Uncommenting the line below will result in an error, as inner_variable is local to inner_function
# print(f"Outside inner_function accessing inner_variable: {inner_variable}")
print(f"Outside inner_function: {outer_variable}")
# Uncommenting the line below will result in an error, as outer_variable is local to outer_function
# print(f"Outside outer_function: {outer_variable}")
outer_function()
Output
Inside inner_function: I am also a local variable
Inside inner_function accessing outer_variable: I am a local variable
Outside inner_function: I am a local variable
What is a Python map() Function?
The Python map() function will return the list of results after providing the given function to every item of the iterable.
Example
# Example using map() function
numbers = [1, 2, 3, 4, 5]
# Define a function to square a number
def square(x):
return x ** 2
# Use map() to apply the square function to each element in the list
squared_numbers = map(square, numbers)
# Output
print(f"Original numbers: {numbers}")
print(f"Squared numbers: {list(squared_numbers)}")
Output
Original numbers: [1, 2, 3, 4, 5]
Squared numbers: [1, 4, 9, 16, 25]
What is the Python memory view() Function?
The Python memory view() function will return the memory view of the given argument.
Example
# Example using memoryview() function
byte_array = bytearray(b"Hello, Memory View!")
# Create a memory view object
memory_view = memoryview(byte_array)
# Output
print(f"Original byte array: {byte_array}")
print(f"Memory view object: {memory_view}")
print(f"Characters in memory view: {list(memory_view)}")
Output
Original byte array: bytearray(b'Hello, Memory View!')
Memory view object: <memory at ...>
Characters in memory view: [72, 101, 108, 108, 111, 44, 32, 77, 101, 109, 111, 114, 121, 32, 86, 105, 101, 119, 33]
What is a Python object()?
The Python object() will return the empty object. Hence, it will act as a base for the classes and carry the built-in properties and the methods that have a default for all the classes.
Example
# Example using object() function
new_object = object()
# Output
print(f"Type of new_object: {type(new_object)}")
print(f"String representation of new_object: {new_object}")
Output
Type of new_object: <class 'object'>
String representation of new_object: <object object at 0x...>
What is the Python open() Function?
The Python open() Function will function to open the file and will return the corresponding file object.
Example
# Example using open() function
file_path = "example.txt"
# Writing to a file
with open(file_path, "w") as file:
file.write("Hello, Python!")
# Reading from the file
with open(file_path, "r") as file:
content = file.read()
# Output
print(f"Content of the file '{file_path}': {content}")
Output
Content of the file 'example.txt': Hello, Python!
What is Python chr() Function?
The Python chr() Function will operate to get the string that will indicate a character and that contains the Unicode code integer. The function will include the integer argument and will show the error if it goes beyond the specified range.
Example
# Example using chr() function with multiple ASCII codes
ascii_codes = [65, 97, 49, 120] # ASCII codes for 'A', 'a', '1', 'x'
# Convert ASCII codes to characters
characters = [chr(code) for code in ascii_codes]
# Output
for code, char in zip(ascii_codes, characters):
print(f"The character corresponding to ASCII code {code} is: {char}")
Output
The character corresponding to ASCII code 65 is: A
The character corresponding to ASCII code 97 is: a
The character corresponding to ASCII code 49 is: 1
The character corresponding to ASCII code 120 is: x
What is the Python complex () function?
The Python complex() function will convert the numbers or strings into the complex number. Hence, this method will have two optional parameters and will return with the complex numbers
Example
# Example using complex() function
real_part = 2.5
imaginary_part = -1
# Create a complex number
complex_number = complex(real_part, imaginary_part)
# Output
print(f"The complex number is: {complex_number}")
print(f"Real part: {complex_number.real}")
print(f"Imaginary part: {complex_number.imag}")
Output
The complex number is: (2.5-1j)
Real part: 2.5
Imaginary part: -1.0
What is the Python delattr () Function?
The Python delattr() function will delete the attribute from the class. Thus, it will take the two parameters. Initially, it will have an object of the class and secondly, it will have the attribute which is needed to be deleted. Thus, after deleting the attribute, it won’t be part of the class and will show an error if it has a class object.
Example
# Example using delattr() function
class Person:
name = "Alice"
age = 25
# Create an instance of the Person class
person = Person()
# Output before using delattr()
print(f"Before using delattr(): {person.__dict__}")
# Delete the 'age' attribute using delattr()
delattr(person, 'age')
# Output after using delattr()
print(f"After using delattr(): {person.__dict__}")
Output
Before using delattr(): {'name': 'Alice', 'age': 25}
After using delattr(): {'name': 'Alice'}
What is the Python dir() Function?
The dir() function in Python gives you a list of attributes (like variables or methods) that an object has. If an object has a special method called __dir__(), Python will use it to get the list of attributes.
Example
class CustomObject:
def __dir__(self):
# Custom method to specify attributes
return ['custom_attr1', 'custom_attr2']
# Create an instance of CustomObject
custom_obj = CustomObject()
# Use dir() to get the list of attributes
attributes = dir(custom_obj)
# Output
print(f"List of attributes using dir(): {attributes}")
Output
List of attributes using dir(): ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__',
What is the Python divmod () Function?
The Python divmod() function will return with the remainder and the quotient of the two numbers. So, the function will have the two numeric arguments and will get the output as a tuple.
Example
# Example using divmod() function
dividend = 20
divisor = 3
# Get the quotient and remainder using divmod()
quotient, remainder = divmod(dividend, divisor)
# Output
print(f"Dividend: {dividend}")
print(f"Divisor: {divisor}")
print(f"Quotient and remainder: {quotient}, {remainder}")
Output
Dividend: 20
Divisor: 3
Quotient and remainder: 6, 2
What is the Python enumerate () Function?
The Python enumerate() function will return with the enumerated object. Hence, it has two parameters initially, the sequence of elements, and the second consists of the start index of the sequence. So, the elements in the sequence will either be through the loop or the next() method.
# Example using enumerate() function
fruits = ['apple', 'banana', 'orange', 'grape']
# Enumerate the list of fruits starting from index 1
enumerated_fruits = enumerate(fruits, start=1)
# Output using a loop
print("Enumerated fruits using a loop:")
for index, fruit in enumerated_fruits:
print(f"Index {index}: {fruit}")
# Output using list comprehension
enumerated_fruits = enumerate(fruits, start=1) # Resetting for list comprehension
list_output = [(index, fruit) for index, fruit in enumerated_fruits]
print("\nEnumerated fruits using list comprehension:")
print(list_output)
Output
Enumerated fruits using a loop:
Index 1: apple
Index 2: banana
Index 3: orange
Index 4: grape
Enumerated fruits using list comprehension:
[(1, 'apple'), (2, 'banana'), (3, 'orange'), (4, 'grape')]
What is Python dict?
Python dict ()acts as a constructor and will make the dictionary.
Example
# Example using dict
student = {
'name': 'Alice',
'age': 18,
'grade': 'A',
'subjects': ['Math', 'Science', 'English']
}
# Output
print("Student Information:")
print(f"Name: {student['name']}")
print(f"Age: {student['age']}")
print(f"Grade: {student['grade']}")
print(f"Subjects: {', '.join(student['subjects'])}")
Output
Student Information:
Name: Alice
Age: 18
Grade: A
Subjects: Math, Science, English
What is the Python filter() Function?
The filter() function in Python helps us pick specific elements from a group of items. It needs two things to work: a rule (function) and a bunch of things to filter (iterable, like a list). The function checks each item and keeps only the ones that follow the rule.
Example
# Example using filter() function
def is_even(num):
return num % 2 == 0
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Use filter() to get even numbers
even_numbers = filter(is_even, numbers)
# Output
print("Original numbers:", numbers)
print("Filtered even numbers:", list(even_numbers))
Output
Original numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Filtered even numbers: [2, 4, 6, 8, 10]
What is a Python hash() Function?
The Python hash() function will return the value of an object. Hence, this Python will evaluate the hash value with the hash algorithm. So, the hash values are the integers and will function to compare the dictionary keys during the dictionary lookup.
Example
# Example using hash() function
string_value = "Hello, Python!"
integer_value = 42
float_value = 3.14
# Get the hash values
hash_string = hash(string_value)
hash_integer = hash(integer_value)
hash_float = hash(float_value)
# Output
print(f"The original string: {string_value}")
print(f"The hash value for the string: {hash_string}")
print(f"\nThe original integer: {integer_value}")
print(f"The hash value for the integer: {hash_integer}")
print(f"\nThe original float: {float_value}")
print(f"The hash value for the float: {hash_float}")
Output
The original string: Hello, Python!
The hash value for the string: -9077442383218711455
The original integer: 42
The hash value for the integer: 42
The original float: 3.14
The hash value for the float: 1152921504606846979
What is the Python help() Function?
The Python help() function will work to get help from the related object and will be passed on during the call. However, it will need an optional parameter for returning the help information. Whereas, if there is no help provided, then the Python help console will be displayed.
Example
# Example function
def greet(name):
"""
This function greets the person with the given name.
Parameters:
name (str): The name of the person to greet.
Returns:
str: A greeting message.
"""
return f"Hello, {name}! Welcome!"
# Using the help function to get information about the greet function
help(greet)
Output
Help on function greet in module __main__:
greet(name)
This function greets the person with the given name.
Parameters:
name (str): The name of the person to greet.
Returns:
str: A greeting message.
What is Python min() Function?
The Python min() will function to receive the smallest element from the elements. Hence, it takes two arguments. Thus, the first consists of the elements that are grouped and the second has a key in it.
Example
# Example using min() function
numbers = [5, 3, 8, 2, 7]
# Using min() to find the minimum value in the list
minimum_value = min(numbers)
# Displaying the result
print("List of numbers:", numbers)
print("Minimum value:", minimum_value)
Output
List of numbers: [5, 3, 8, 2, 7]
Minimum value: 2
What is the Python set () Function?
The set () function is referred to as the built-in class and hence, this function consists of the constructor of this class. So, it will make a new set with the elements that are passed during the call. Hence, it will take an iterable object which will act as an argument and then return as a new set object.
Example
# Example using set() function
fruits_list = ['apple', 'orange', 'banana', 'apple', 'kiwi']
# Using set() to create a set from the list
fruits_set = set(fruits_list)
# Displaying the result
print("List of fruits:", fruits_list)
print("Set of fruits:", fruits_set)
Output
List of fruits: ['apple', 'orange', 'banana', 'apple', 'kiwi']
Set of fruits: {'orange', 'kiwi', 'apple', 'banana'}
What is a Python hex() Function?
The Python hex() function will function to create the hex value of the integer argument. So, it will take an integer argument and then return with the integer that will be turned into the hexadecimal string.
Example
# Example using hex() function
decimal_number = 255
# Using hex() to convert the decimal number to hexadecimal
hexadecimal_string = hex(decimal_number)
# Displaying the result
print("Decimal number:", decimal_number)
print("Hexadecimal representation:", hexadecimal_string)
Output
Decimal number: 255
Hexadecimal representation: 0xff
What is Python id() Function?
The Python id() function will return with the identity of the object. This is referred to as a unique integer. This function will take an argument as an object and will return the unique integer number that will stand for the identity.
Example
# Example using id() function
value1 = 42
value2 = "Hello, World!"
# Displaying the identity of the objects
print("Identity of value1:", id(value1))
print("Identity of value2:", id(value2))
Output
Identity of value1: 140710617731840
Identity of value2: 140710603225904
What is the Python setattr () Function?
This Python set attr () will function to put a value to the object attribute. So, it will take three arguments such as object, string, and arbitrary value, and won’t return any.
Example
# Example using setattr() function
class Person:
pass
# Creating an instance of the Person class
person_obj = Person()
# Using setattr() to set attributes on the object
setattr(person_obj, 'name', 'John Doe')
setattr(person_obj, 'age', 30)
# Displaying the attributes
print("Person's name:", getattr(person_obj, 'name'))
print("Person's age:", getattr(person_obj, 'age'))
Output
Person's name: John Doe
Person's age: 30
What is Python’s next() Function?
The Python next() function will get the next item from the collection. So, it has two arguments such as iterator and the default value . Thus, it will return the element.
Example
# Example using next() function
numbers = iter([1, 2, 3, 4, 5])
# Using next() to get the next item from the iterator
next_number = next(numbers)
# Displaying the result
print("Next number:", next_number)
Output
Next number: 1
What is the Python input() Function?
The Python input() function will get the input from the user. Hence, it will ask for the user’s input and then read the line. Hence, after reading the data, it will turn the string and will return it. It will detect EOFError when the EOF is read.
Example
# Example using input() function
user_name = input("Enter your name: ")
# Displaying the user input
print("Hello, " + user_name + "! Welcome!")
Output
Enter your name: John
Hello, John! Welcome!
What is Python int() Function?
Python int() function will receive an integer value. Thus, it will return with the expression which will be turned into the integer number. So, if the argument has a floating point and will be turned the number into the long type.
Example
# Example using int() function
numeric_string = "42"
# Using int() to convert the string to an integer
numeric_value = int(numeric_string)
# Displaying the result
print("Original string:", numeric_string)
print("Converted integer:", numeric_value)
Output
Original string: 42
Converted integer: 42
What is a Python isinstance () Function?
The Python isinstance() function will monitor if the object is an instance of the class. But, if the object is from the class and thus it will come true. Or else, it will come false. Additionally, it will return true when the class is a subclass.
Whereas, the isinstance will have two arguments such as object and class info.
Example
# Example using isinstance() function
value = 42
# Checking if the value is an instance of the int class
is_int_instance = isinstance(value, int)
# Displaying the result
print("Value:", value)
print("Is an instance of int:", is_int_instance)
Output
Value: 42
Is an instance of int: True
What is Python oct() Function?
The Python oct() function will help to convert the octal value of the integer number. So, this method will take an argument and then return with the integer. It will be turned into the octal string.
Example
# Example using oct() function
decimal_number = 42
# Using oct() to convert the decimal number to octal
octal_representation = oct(decimal_number)
# Displaying the result
print("Decimal number:", decimal_number)
print("Octal representation:", octal_representation)
Output
Decimal number: 42
Octal representation: 0o52
What is the Python ord() Function?
The ord() function in Python helps to return the integer which will stand for the Unicode character.
# Example using ord() function
character = 'A'
# Using ord() to get the Unicode code point of the character
unicode_code_point = ord(character)
# Displaying the result
print("Character:", character)
print("Unicode code point:", unicode_code_point)
Output
Character: A
Unicode code point: 65
What is the Python Pow () Function?
The pow()
function in Python helps us find the result when a number is raised to a power.
# Example using pow() function
base = 2
exponent = 3
# Using pow() to find the result of 2 raised to the power of 3
result = pow(base, exponent)
# Displaying the result
print(f"{base} to the power of {exponent} is: {result}")
Output
2 to the power of 3 is: 8
What is the Python Print () Function?
The Python print() will help to print the given object to the screen.
Example
# Example using print() function
name = "John"
age = 25
# Using print() to display information
print("Name:", name)
print("Age:", age)
Output
Name: John
Age: 25
What is the Python range () Function?
The Python range() function will help to return the immutable sequence of the numbers which begin from 0 by default, that will added by 1 and terminated at the specified number.
Example
# Example using range() function
# Generate a sequence of numbers from 0 to 4 (excluding 5)
numbers_sequence = range(5)
# Displaying the result
print("Generated sequence:", list(numbers_sequence))
Output
Generated sequence: [0, 1, 2, 3, 4]
What is the Python reversed() Function?
The reversed() function will help to return the reversed iterator of the given sequence.
Example
# Example using reversed() directly in a loop
for num in reversed([1, 2, 3, 4, 5]):
print(num, end=' ')
Output
5 4 3 2 1
What is a Python round Function?
The Python round() function will allow us to round off the digits of the number and will return the floating point number.
Example
# Example using round() function
original_number = 3.14159
# Using round() to round the number to 2 decimal places
rounded_number = round(original_number, 2)
# Displaying the result
print("Original number:", original_number)
print("Rounded number:", rounded_number)
Output
Original number: 3.14159
Rounded number: 3.14
What is Python issubclass () Function?
The Python issubclass () function will allow us to return true if the object argument is referred to as the subclass of the second class.
Example
# Example with multiple inheritance
class Mammal:
pass
class Canine(Animal, Mammal):
pass
# Checking if Canine is a subclass of both Animal and Mammal
is_canine_subclass = issubclass(Canine, (Animal, Mammal))
# Displaying the result
print("Is Canine a subclass of Animal and Mammal?", is_canine_subclass)
Output
Is Canine a subclass of Animal and Mammal? True
What is Python str?
The Python str () function will enable us to turn the specified value into the string.
# Example with a list
my_list = [1, 2, 3]
# Using str() to convert the list to a string
list_representation = str(my_list)
# Displaying the result
print("Original list:", my_list)
print("String representation of the list:", list_representation)
Output
Original list: [1, 2, 3]
String representation of the list: [1, 2, 3]
What is the Python tuple() Function?
The Python tuple() function will allow us to make the tuple object.
Example
# Example of creating and using a tuple
my_tuple = (1, 'apple', 3.14, True)
# Displaying the tuple
print("Tuple:", my_tuple)
# Accessing elements in a tuple
print("First element:", my_tuple[0])
print("Second element:", my_tuple[1])
# Slicing a tuple
subset_tuple = my_tuple[1:3]
print("Subset of the tuple:", subset_tuple)
Output
Tuple: (1, 'apple', 3.14, True)
First element: 1
Second element: apple
Subset of the tuple: ('apple', 3.14)
What is Python type() Function?
The Python type () function will allow us to return the type of the specified object when the single argument is passed to the type () built-in function.
Example
# Example using type() function
value1 = 42
value2 = 'Hello, World!'
value3 = [1, 2, 3]
value4 = {'a': 1, 'b': 2}
# Using type() to get the type of each object
type_of_value1 = type(value1)
type_of_value2 = type(value2)
type_of_value3 = type(value3)
type_of_value4 = type(value4)
# Displaying the result
print("Type of value1:", type_of_value1)
print("Type of value2:", type_of_value2)
print("Type of value3:", type_of_value3)
print("Type of value4:", type_of_value4)
Output
Type of value1: <class 'int'>
Type of value2: <class 'str'>
Type of value3: <class 'list'>
Type of value4: <class 'dict'>
What is the Python vars() Function?
The Python vars() function will allow us to return the __dict__ attribute of the particular object.
Example
# Example using vars() function
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Creating an instance of the Person class
person_object = Person(name="John", age=25)
# Using vars() to get the attributes and their values
attributes_dict = vars(person_object)
# Displaying the result
print("Attributes and values:", attributes_dict)
Output
Attributes and values: {'name': 'John', 'age': 25}
What is the Python zip() Function?
The Python zip() function will help to return the zip object and thus will analyze the similar index of the multiple containers, Hence, it will take the iterable that can create an iterator depending on the iterable passed.
Example
# Example using zip() function
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 22]
# Using zip() to combine two lists
zipped_data = zip(names, ages)
# Converting the result to a list for better visualization
result_list = list(zipped_data)
# Displaying the result
print("Original lists:")
print("Names:", names)
print("Ages:", ages)
print("\nZipped result:")
print(result_list)
Output
Original lists:
Names: ['Alice', 'Bob', 'Charlie']
Ages: [25, 30, 22]
Zipped result:
[('Alice', 25), ('Bob', 30), ('Charlie', 22)]
Conclusion
Python’s built-in functions are fundamental tools that simplify coding tasks and are crucial for any programmer. This article will improve your skills and knowledge of the built-in functions.
Python Built-in Functions -FAQ
Q1. What are the most used Python inbuilt functions?
Ans. The Python inbuilt function include print(), abs(), round(), min(), max(), sorted(), sum(), and len().
Q2.How many structures are there in Python?
Ans. The basic Python data structures in Python are list, set, tuples, and dictionary.
Q3.What are the 4 types of functions in Python?
Ans. Those 4 types of functions are built-in Functions, User-defined Functions, Recursive Functions, and Lambda Functions.
Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together