Built-in functions in Python refer to those functions that come with predefined capabilities within the language. The Python interpreter includes a variety of functions that are readily available for immediate use. These functions are collectively referred to as Built-in Functions. Below is a compilation of various built-in functions available in Python:
Python abs Function
The abs function in Python serves the purpose of providing the absolute value of a given number. It accepts just a single argument, which is the number for which the absolute value is to be calculated. This argument can either be an integer or a float. In cases where the input is a complex number, the abs function will yield its magnitude.
Python abs Function Example
Consider the following example to illustrate how the abs function operates in Python.
# integer number
integer = -20
print('Absolute value of -40 is:', abs(integer))
# floating number
floating = -20.83
print('Absolute value of -40.83 is:', abs(floating))
Output:
Absolute value of -20 is: 20
Absolute value of -20.83 is: 20.83
Python all Function
The all function in Python takes an iterable object, which can include types such as lists, dictionaries, and more. It evaluates the items within the provided iterable and returns True only if every item is true. If any item is false, the function returns False. In cases where the iterable object is empty, the all function will return True.
Python all Function Example
To illustrate the functionality of the all method in Python, let's consider a specific example.
# all values true
k = [1, 3, 4, 6]
print(all(k))
# all values false
k = [0, False]
print(all(k))
# one false value
k = [1, 3, 7, 0]
print(all(k))
# one true value
k = [0, False, 5]
print(all(k))
# empty iterable
k = []
print(all(k))
Output:
True
False
False
False
True
Python bin Function
The bin function in Python serves the purpose of delivering the binary representation of a given integer. The output consistently begins with the prefix 0b.
Python bin Function Example
To demonstrate the functionality of the bin function in Python, let us consider a specific example.
x = 10
y = bin(x)
print (y)
Output:
0b1010
Python bool Function
The Python function bool transforms a given value into a Boolean type, representing either True or False, by employing the conventional truth evaluation method.
Python bool Function Example
To demonstrate the usage of the bool function in Python, let us consider an example.
test1 = []
print(test1,'is',bool(test1))
test1 = [0]
print(test1,'is',bool(test1))
test1 = 0.0
print(test1,'is',bool(test1))
test1 = None
print(test1,'is',bool(test1))
test1 = True
print(test1,'is',bool(test1))
test1 = 'Easy string'
print(test1,'is',bool(test1))
Output:
[] is False
[0] is True
0.0 is False
None is False
True is True
Easy string is True
Python bytes
The Python function bytes serves the purpose of creating and returning a bytes object. This function provides an immutable alternative to the bytearray function.
It is capable of generating an empty bytes object with the defined size.
Python bytes Function Example
To exemplify the usage of the bytes function in Python, let us consider the following scenario.
string = "Hello World."
array = bytes(string, 'utf-8')
print(array)
Output:
b ' Hello World.'
Python callable Function
The callable function in Python is a built-in utility that evaluates whether the provided object seems to be callable. It returns true if the object is indeed callable, and false if it is not.
Python callable Function Example
Consider an example that demonstrates the usage of the callable function in Python.
x = 8
print(callable(x))
Output:
Python compile Function
The compile function in Python accepts source code as its input and produces a code object, which can subsequently be executed using the exec function.
Python compile Function Example
To demonstrate the functionality of the compile function in Python, let us consider an example.
# compile string source to code
code_str = 'x=5\ny=10\nprint("sum =",x+y)'
code = compile(code_str, 'sum.py', 'exec')
print(type(code))
exec(code)
exec(x)
Output:
<class 'code'>
sum = 15
Python exec Function
The exec function in Python facilitates the dynamic execution of Python code, which can be provided as either a string or object code. This function is capable of handling substantial segments of code, in contrast to the eval function, which is limited to evaluating a single expression.
Python exec Function Example
Let’s consider an example to demonstrate the functionality of the exec function in Python.
x = 8
exec('print(x==8)')
exec('print(x+4)')
Output:
True
12
Python sum Function
True to its name, the Python sum function serves the purpose of calculating the total of numbers contained within an iterable, such as a list.
Python sum Function Example
Let us consider an example to demonstrate the sum function in Python.
s = sum([1, 2,4 ])
print(s)
s = sum([1, 2, 4], 10)
print(s)
Output:
Python any Function
The any function in Python generates a return value of True if at least one element within an iterable evaluates to true. If no elements are true, it will return False.
Python any Function Example
To demonstrate the functionality of the any function in Python, let us consider an example.
l = [4, 3, 2, 0]
print(any(l))
l = [0, False]
print(any(l))
l = [0, False, 5]
print(any(l))
l = []
print(any(l))
Output:
True
False
True
False
Python ascii Function
The ascii function in Python produces a string that provides a printable representation of a given object, while also converting any non-ASCII characters within that string into their respective escape sequences, which may include \x, \u, or \U formats.
Python ascii Function Example
To illustrate the usage of the ascii function in Python, let us consider a specific example.
normalText = 'Python is interesting'
print(ascii(normalText))
otherText = 'Python is interesting'
print(ascii(otherText))
print('Pyth\xf6n is interesting')
Output:
'Python is interesting'
'Pyth\xf6n is interesting'
Python is interesting
Python bytearray Function
The Python function bytearray generates a bytearray object and is capable of converting various objects into bytearray instances, or it can initialize an empty bytearray object of a defined size.
Python bytearray Function Example
Consider the following example to demonstrate the functionality of the bytearray method in Python.
string = "Python is a programming language."
# string with encoding 'utf-8'
arr = bytearray(string, 'utf-8')
print(arr)
Output:
bytearray(b'Python is a programming language.')
Python eval Function
The eval function in Python evaluates the expression provided to it and executes the corresponding Python code within the context of the program.
Python eval Function Example
To demonstrate the functionality of the eval function in Python, we will consider an example.
x = 8
print(eval('x + 1'))
Output:
Python float Function
The float function in Python converts a number or a string into a floating-point number.
Python float Example Function
To demonstrate the usage of the float function in Python, let's consider an example.
# for integers
print(float(9))
# for floats
print(float(8.19))
# for string floats
print(float("-24.27"))
# for string floats with whitespaces
print(float(" -17.19\n"))
# string float error
print(float("xyz"))
Output:
9.0
8.19
-24.27
-17.19
ValueError: could not convert string to float: 'xyz'
Python format Function
The format function in Python produces a formatted version of the specified value.
Python format Function Example
Let’s consider an example to demonstrate the usage of the format function in Python.
# d, f and b are a type
# integer
print(format(123, "d"))
# float arguments
print(format(123.4567898, "f"))
# binary format
print(format(12, "b"))
Output:
123
123.456790
1100
Python frozenset
The frozenset function in Python produces an immutable frozenset object that is created using elements derived from the specified iterable.
Python frozenset Function Example
Let us consider a practical example to illustrate the usage of the frozenset function in Python.
# tuple of letters
letters = ('m', 'r', 'o', 't', 's')
fSet = frozenset(letters)
print('Frozen set is:', fSet)
print('Empty frozen set is:', frozenset())
Output:
Frozen set is: frozenset({'o', 'm', 's', 'r', 't'})
Empty frozen set is: frozenset()
Python getattr Function
The getattr function in Python retrieves the value associated with a specified attribute of an object. In the event that the attribute does not exist, it provides a default value instead.
Python getattr Function Example
Consider the following example to demonstrate the usage of the getattr function in Python.
class Details:
age = 22
name = "Amit"
details = Details()
print('The age is:', getattr(details, "age"))
print('The age is:', details.age)
Output:
The age is: 22
The age is: 22
Python globals Function
The globals function in Python provides a dictionary that represents the current global symbol table.
A Symbol table is characterized as a data structure that holds all pertinent information regarding a program. This encompasses details such as variable names, methods, classes, and more.
Python globals Function Example
Let's consider an example to demonstrate the functionality of the globals function in Python.
age = 22
globals()['age'] = 22
print('The age is:', age)
Output:
The age is: 22
Python iter Function
The iter function in Python is utilized to produce an iterator object. This function generates an object that allows for iteration over its elements sequentially, one at a time.
Python iter Function Example
Let us consider an example to demonstrate the iter function in Python.
# list of numbers
list = [1,2,3,4,5]
listIter = iter(list)
# prints '1'
print(next(listIter))
# prints '2'
print(next(listIter))
# prints '3'
print(next(listIter))
# prints '4'
print(next(listIter))
# prints '5'
print(next(listIter))
Output:
1
2
3
4
5
Python len Function
The len function in Python serves the purpose of providing the length of an object, which is defined as the count of items contained within it.
Python len Function Example
To demonstrate the use of the len function in Python, let's consider an example.
strA = 'Python'
print(len(strA))
Output:
Python list Function
The Python list creates a list in Python.
Python list Function Example
For the purpose of demonstrating the list function in Python, let's consider an example.
# empty list
print(list())
# string
String = 'abcde'
print(list(String))
# tuple
Tuple = (1,2,3,4,5)
print(list(Tuple))
# list
List = [1,2,3,4,5]
print(list(List))
Output:
[]
['a', 'b', 'c', 'd', 'e']
[1,2,3,4,5]
[1,2,3,4,5]
Python locals Function
The locals function in Python modifies and returns the dictionary representing the current local symbol table.
A symbol table is characterized as a data structure that encompasses all essential information pertaining to the program. This includes details such as variable identifiers, method definitions, class specifications, and more.
Python locals Function Example
Consider the following example to demonstrate the functionality of the locals function in Python.
def localsAbsent():
return locals()
def localsPresent():
present = True
return locals()
print('localsNotPresent:', localsAbsent())
print('localsPresent:', localsPresent())
Output:
localsAbsent: {}
localsPresent: {'present': True}
Python map Function
The map function in Python is utilized to produce a list of outcomes by applying a specified function to every element within an iterable, such as a list, tuple, or similar structures.
Python map Function Example
def calculateAddition(n):
return n+n
numbers = (1, 2, 3, 4)
result = map(calculateAddition, numbers)
print(result)
# converting map object to set
numbersAddition = set(result)
print(numbersAddition)
Output:
<map object at 0x7fb04a6bec18>
{8, 2, 4, 6}
Python memoryview Function
The memoryview function in Python generates a memoryview object based on the specified argument.
Python memoryview Function Example
#A random bytearray
randomByteArray = bytearray('ABC', 'utf-8')
mv = memoryview(randomByteArray)
# access the memory view's zeroth index
print(mv[0])
# It create byte from memory view
print(bytes(mv[0:2]))
# It create list from memory view
print(list(mv[0:3]))
Output:
65
b'AB'
[65, 66, 67]
Python object
The Python function object generates an instance of an empty object. This serves as a foundational element for all classes and encompasses the inherent properties and methods that are standard across all classes.
Python object Function Example
python = object()
print(type(python))
print(dir(python))
Output:
<class 'object'>
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__']
Python open Function
The open function in Python is utilized to access a file and subsequently returns an associated file object.
Python open Function Example
# opens python.text file of the current directory
f = open("python.txt")
# specifying full path
f = open("C:/Python33/README.txt")
Output:
Since the mode is omitted, the file is opened in 'r' mode; opens for reading.
Python chr Function
The chr function in Python serves the purpose of obtaining a string that corresponds to a character associated with a Unicode code point. For instance, invoking chr(97) will yield the string 'a'. This function accepts an integer as its argument and will raise an error if the provided value falls outside the defined range. The typical range for the argument is between 0 and 1,114,111.
Python chr Function Example
Let’s consider an example to demonstrate the chr function in Python.
# Calling function
result = chr(102) # It returns string representation of a char
result2 = chr(112)
# Displaying result
print(result)
print(result2)
# Verify, is it string type?
print("is it string type:", type(result) is str)
Output:
ValueError: chr() arg not in range(0x110000)
Python complex Function
The complex function in Python is utilized for transforming numbers or strings into complex numbers. This function accepts two optional arguments and produces a complex number as its output. The initial argument represents the real component, while the second argument signifies the imaginary component.
Python complex Function Example
To demonstrate the usage of the complex function in Python, let's consider a specific example.
# Python complex() function example
# Calling function
a = complex(1) # Passing single parameter
b = complex(1,2) # Passing both parameters
# Displaying result
print(a)
print(b)
Output:
(1.5+0j)
(1.5+2.2j)
Python delattr Function
The delattr function in Python serves the purpose of removing an attribute from a specified class. This function accepts two arguments: the initial argument is an instance of the class, while the second argument refers to the attribute intended for deletion. Once the attribute has been removed, it becomes inaccessible within the class, and attempting to reference it through the class instance will result in an error.
Python delattr Function Example
To demonstrate the delattr function in Python, let us consider an example.
class Student:
id = 101
name = "Chen"
email = "pranshu@abc.com"
# Declaring function
def getinfo(self):
print(self.id, self.name, self.email)
s = Student()
s.getinfo()
delattr(Student,'course') # Removing attribute which is not available
s.getinfo() # error: throws an error
Output:
101 Pranshu[email protected]AttributeError: course
Python dir Function
The dir function in Python provides a list of names that exist within the current local context. When invoked on an object that possesses a method named dir, this specific method will be executed and is expected to return a list of the object's attributes. It accepts a single argument that pertains to the type of the object.
Python dir Function Example
Consider the following example to demonstrate the functionality of the dir function in Python.
# Calling function
att = dir()
# Displaying result
print(att)
Output:
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__']
Python divmod Function
The divmod function in Python serves the purpose of calculating both the quotient and the remainder when dividing two numbers. This function requires two numeric inputs and yields a tuple as its output. Both of the provided arguments must be numeric and are mandatory for the function to operate correctly.
Python divmod Function Example
To demonstrate the functionality of the divmod function in Python, let us consider an example.
# Python divmod() function example
# Calling function
result = divmod(10,2)
# Displaying result
print(result)
Output:
(5, 0)
Python enumerate Function
The enumerate function in Python produces an enumerated object. It accepts two arguments: the initial one is a collection of elements, while the second one specifies the starting index of the sequence. We can access the elements in the sequence using either a loop or by utilizing the next method.
Python enumerate Function Example
To demonstrate the use of the enumerate function in Python, let's consider an example.
# Calling function
result = enumerate([1,2,3])
# Displaying result
print(result)
print(list(result))
Output:
<enumerate object at 0x7ff641093d80>
[(0, 1), (1, 2), (2, 3)]
Python dict Function
The Python dict function is a constructor that creates a dictionary. Python dictionary provides three different constructors to create a dictionary:
- If no argument is passed, it creates an empty dictionary.
- If a positional argument is given, a dictionary is created with the same key-value pairs. Otherwise, pass an iterable object.
- If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument.
Python dict Function Example
Let’s consider an example to illustrate the use of the dict function in Python.
# Calling function
result = dict() # returns an empty dictionary
result2 = dict(a=1,b=2)
# Displaying result
print(result)
print(result2)
Output:
{}
{'a': 1, 'b': 2}
Python filter Function
The filter function in Python is utilized to retrieve specific elements based on a condition. This function requires two parameters: the first is a callable (function), and the second is an iterable collection. The filter function outputs a sequence containing only those elements from the iterable for which the provided function yields a truthy result.
The initial argument may be null if the function is not accessible and exclusively yields elements that evaluate to true.
Python filter Function Example
To demonstrate the filter function in Python, let’s consider an example.
# Python filter() function example
def filterdata(x):
if x>5:
return x
# Calling function
result = filter(filterdata,(1,2,6))
# Displaying result
print(list(result))
Output:
Python hash Function
The hash function in Python serves the purpose of retrieving the hash value of a given object. This value is computed by utilizing a hashing algorithm. Hash values are represented as integers and play a crucial role in comparing keys within dictionaries during the process of dictionary lookups. The types that can be hashed are restricted to those listed below:
Types that are hashable include:
- boolean
- integer
- long integer
- floating-point number
- string
- Unicode string
- tuple
- code object.
Python hash Function Example
Consider an example that demonstrates the use of the hash function in Python.
# Calling function
result = hash(21) # integer value
result2 = hash(22.2) # decimal value
# Displaying result
print(result)
print(result2)
Output:
21
461168601842737174
Python help Function
The help function in Python serves the purpose of providing assistance regarding the object that is supplied as an argument during its invocation. It accepts an optional parameter and returns relevant help information. In the absence of any argument, it presents the Python help console. Internally, it invokes Python's help functionality.
Python help Function Example
Consider the following example to demonstrate the functionality of the help function in Python.
# Calling function
info = help() # No argument
# Displaying result
print(info)
Output:
Welcome to Python 3.5's help utility!
Python min Function
The min function in Python is utilized to retrieve the minimal element from a given collection. This function accepts two parameters: the initial parameter is a collection of items, while the second one is a key function, which allows for custom comparison. It returns the smallest element found within the specified collection.
Python min Function Example
To demonstrate the functionality of the min function in Python, let’s consider an example.
# Calling function
small = min(2225,325,2025) # returns smallest element
small2 = min(1000.25,2025.35,5625.36,10052.50)
# Displaying result
print(small)
print(small2
Output:
325
1000.25
Python set Function
Within Python, a set is a fundamental class, and the set function serves as the constructor for this class. This function is utilized to generate a new set by incorporating elements provided during its invocation. It accepts an iterable object as its parameter and yields a brand-new set object as the result.
Python set Function Example
Allow us to examine an example that demonstrates the use of the set function in Python.
# Calling function
result = set() # empty set
result2 = set('12')
result3 = set('Example')
# Displaying result
print(result)
print(result2)
print(result3)
Output:
set()
{'2', '1'}
{'i', 't', 'h', 'e', 'p', 'o', 'c', 'n', 'T'}
Python hex Function
The hex function in Python is utilized to produce the hexadecimal representation of an integer input. It accepts an integer as an argument and yields a string that represents the integer in hexadecimal format. If you require the hexadecimal representation of a floating-point number, you should utilize the float.hex method instead.
Python hex Function Example
To demonstrate the usage of the hex function in Python, let us consider an example.
# Calling function
result = hex(1)
# integer value
result2 = hex(342)
# Displaying result
print(result)
print(result2)
Output:
0x1
0x156
Python id Function
The id function in Python provides the identity of a given object. This identity is represented as a unique integer. The function accepts an object as its parameter and yields a distinctive integer that signifies its identity. It is important to note that two objects that do not share overlapping lifetimes can have identical id values.
Python id Function Example
# Calling function
val = id("Example") # string object
val2 = id(1200) # integer object
val3 = id([25,336,95,236,92,3225]) # List object
# Displaying result
print(val)
print(val2)
print(val3)
Output:
136794813706224
136794813580496
136794813641408
Python setattr Function
The setattr function in Python is utilized to assign a value to an attribute of an object. This function requires three parameters: an object, a string that represents the name of the attribute, and a value of any type. It does not return any value. This function is particularly useful when there is a need to introduce a new attribute to an object and assign a specific value to it.
Python setattr Function Example
To demonstrate the functionality of the setattr method in Python, let’s consider an example.
class Student:
id = 0
name = ""
def __init__(self, id, name):
self.id = id
self.name = name
student = Student(102,"Sohan")
print(student.id)
print(student.name)
#print(student.email) product error
setattr(student, 'email','sohan@abc.com') # adding new attribute
print(student.email)
Output:
102
Sohan
[email protected]
Python hasattr Function
In Python, the built-in function hasattr serves the purpose of determining if an object contains a particular attribute. It yields True when the attribute is present and False when it is absent.
Python hasattr Function Example
Let’s consider an example to demonstrate the usage of the hasattr function in Python.
class Car:
brand = "Ford"
model = "Mustang"
my_car = Car()
# It checks if the car's brand attribute exists in the Car class
print(hasattr(Car, "brand"))
# It checks if the car's model attribute exists in the my_car object
print(hasattr(my_car, "model"))
# It checks for an attribute that does not exist
print(hasattr(my_car, "year"))
Output:
True
True
False
Python slice Function
The slice function in Python serves the purpose of extracting a portion of elements from a given collection. Python offers two variations of the slice function. The initial variation accepts a single parameter, whereas the second variation takes three parameters and produces a slice object. This slice object can then be utilized to retrieve a specific subsection from the collection.
Python slice Function Example
To demonstrate the functionality of the slice method in Python, we will consider an example.
# Calling function
result = slice(5) # returns slice object
result2 = slice(0,5,3) # returns slice object
# Displaying result
print(result)
print(result2)
Output:
slice(None, 5, None)
slice(0, 5, 3)
Python sorted Function
The sorted function in Python is utilized for arranging elements. By default, it organizes items in ascending order, although it can also arrange them in descending order. This function accepts four parameters and produces a collection that is sorted. When applied to a dictionary, it sorts solely the keys instead of the values.
Python sorted Function Example
To demonstrate the functionality of the sorted method in Python, we will use an example.
str = "Example" # declaring string
# Calling function
sorted1 = sorted(str) # sorting string
# Displaying result
print(sorted1)
Output:
['T', 'T', 'c', 'e', 'h', 'i', 'n', 'o', 'p', 't']
Python next Function
The next function in Python is utilized to retrieve the subsequent item from an iterable collection. It accepts two parameters: an iterator and an optional default value, and it outputs the next element in the sequence.
This approach invokes the iterator and generates an error when no items are available. To prevent this error from occurring, we can specify a default value.
Python next Function Example
To illustrate the usage of the bin function in Python, let's consider the following example.
number = iter([256, 32, 82]) # Creating iterator
# Calling function
item = next(number)
# Displaying result
print(item)
# second item
item = next(number)
print(item)
# third item
item = next(number)
print(item)
Output:
256
32
82
Python input Function
The input function in Python is utilized to capture input from the user. It presents a prompt for user input and captures an entire line. Once the data has been read, it transforms it into a string format and returns the result. If an end-of-file (EOF) is encountered, it raises an EOFError.
Python input Function Example
For the purpose of demonstrating the input function in Python, let us consider a practical example.
# Calling function
val = input("Enter a value: ")
# Displaying result
print("You entered:",val)
Output:
Enter a value: 45
You entered: 45
Python int Function
The int function in Python is employed to obtain an integer value. This function yields an expression transformed into an integer format. In cases where the argument provided is a floating-point number, the conversion process truncates the decimal portion. Additionally, if the argument exceeds the allowable range for integers, the function converts the number to a long type.
If the value is not a numeric type or if a base is specified, then the value needs to be represented as a string.
Python int Function Example
For our demonstration, we will examine the int function in Python.
# Calling function
val = int(10) # integer value
val2 = int(10.52) # float value
val3 = int('10') # string value
# Displaying result
print("integer values :",val, val2, val3)
Output:
integer values : 10 10 10
Python isinstance Function
The isinstance function in Python serves to determine if a specified object is an instance of a particular class. If the object is an instance of the class in question, it yields a true value. Conversely, it returns false if it does not belong to that class. Additionally, it also returns true if the class in question is a subclass of the specified class.
The isinstance function accepts two parameters: the object and classinfo, and it subsequently returns a boolean value of either True or False.
Python isinstance Function Example
Consider an example to demonstrate the functionality of the isinstance method in Python.
class Student:
id = 101
name = "Sarah"
def __init__(self, id, name):
self.id=id
self.name=name
student = Student(1010,"John")
lst = [12,34,5,6,767]
# Calling function
print(isinstance(student, Student)) # isinstance of Student class
print(isinstance(lst, Student))
Output:
True
False
Python oct Function
The oct function in Python serves the purpose of obtaining the octal representation of an integer. This function accepts a single argument and produces a string that represents the integer in octal format. If the provided argument is not of integer type, it raises a TypeError.
Python oct Function Example
Let's consider an example to demonstrate the use of the oct function in Python.
# Calling function
val = oct(10)
# Displaying result
print("Octal value of 10:",val)
Output:
Octal value of 10: 0o12
Python ord Function
The ord function in Python provides an integer value that corresponds to the Unicode code point of a specified Unicode character.
Python ord Function Example
Consider the following example to demonstrate the use of the ord function in Python.
# Code point of an integer
print(ord('8'))
# Code point of an alphabet
print(ord('R'))
# Code point of a character
print(ord('&'))
Output:
56
82
38
Python pow Function
The pow function in Python serves the purpose of calculating the exponentiation of a number. It provides the result of x raised to the power of y. In cases where a third parameter (z) is supplied, it yields the result of x to the power of y modulo z, represented as (x, y) % z.
Python pow Function Example
Let us consider an example to demonstrate the pow function in Python.
# positive x, positive y (x**y)
print(pow(4, 2))
# negative x, positive y
print(pow(-4, 2))
# positive x, negative y (x**-y)
print(pow(4, -2))
# negative x, negative y
print(pow(-4, -2))
Output:
16
16
0.0625
0.0625
Python print Function
The print function in Python outputs the specified object to the display or other standard output devices.
Python print Function Example
Let us consider an example to demonstrate the print function in Python.
print("Python is programming language.")
x = 7
# Two objects passed
print("x =", x)
y = x
# Three objects passed
print('x =', x, '= y')
Output:
Python is programming language.
x = 7
x = 7 = y
Python range Function
The range function in Python generates an immutable series of integers, beginning at 0 by default, increasing by 1 (also by default), and concluding at a designated number.
Python range Function Example
To demonstrate the functionality of the range function in Python, let's consider an example.
# empty range
print(list(range(0)))
# using the range(stop)
print(list(range(4)))
# using the range(start, stop)
print(list(range(1,7 )))
Output:
[]
[0, 1, 2, 3]
[1, 2, 3, 4, 5, 6]
Python reversed Function
The reversed function in Python provides an iterator that yields the elements of the specified sequence in reverse order.
Python reversed Function Example
To demonstrate the functionality of the reversed function in Python, let's consider a specific example.
# for string
String = 'Python'
print(list(reversed(String)))
# for tuple
Tuple = ('J', 'a', 'v', 'a')
print(list(reversed(Tuple)))
# for range
Range = range(8, 12)
print(list(reversed(Range)))
# for list
List = [1, 2, 7, 5]
print(list(reversed(List)))
Output:
['a', 'v', 'a', 'J']
['a', 'v', 'a', 'J']
[11, 10, 9, 8]
[5, 7, 2, 1]
Python round Function
The round function in Python is designed to round the digits of a numerical value and subsequently return the result as a floating-point number.
Python round Function Example
We can use a specific example to demonstrate how the round function operates in Python.
# for integers
print(round(10))
# for floating point
print(round(10.8))
# even choice
print(round(6.6))
Output:
10
11
7
Python issubclass Function
The Python function issubclass evaluates to true if the first argument, which is an object, is identified as a subclass of the class provided as the second argument.
Python issubclass Function Example
To demonstrate the functionality of the issubclass method in Python, let us consider a practical example.
class Rectangle:
def __init__(rectangleType):
print('Rectangle is a ', rectangleType)
class Square(Rectangle):
def __init__(self):
Rectangle.__init__('square')
print(issubclass(Square, Rectangle))
print(issubclass(Square, list))
print(issubclass(Square, (list, Rectangle)))
print(issubclass(Rectangle, (list, Rectangle)))
Output:
True
False
True
True
Python str Function
The Python function str transforms a given value into its string representation.
Python str Function Example
Let's consider an example to demonstrate the usage of the str function in Python.
str('4')
Output:
Python tuple Function
The tuple function in Python serves to generate a tuple object.
Python tuple Function Example
t1 = tuple()
print('t1=', t1)
# creating a tuple from a list
t2 = tuple([1, 6, 9])
print('t2=', t2)
# creating a tuple from a string
t1 = tuple('Python')
print('t1=',t1)
# creating a tuple from a dictionary
t1 = tuple({4: 'four', 5: 'five'})
print('t1=',t1)
Output:
t1= ()
t2= (1, 6, 9)
t1= ('J', 'a', 'v', 'a')
t1= (4, 5)
Python type
The built-in function type in Python will return the type of a given object when it is provided with a single argument. Conversely, if it is supplied with three arguments, it generates a new type object.
Python type Function Example
To demonstrate the functionality of the type function in Python, let's consider an example.
List = [4, 5]
print(type(List))
Dict = {4: 'four', 5: 'five'}
print(type(Dict))
class Python:
a = 0
InstanceOfPython = Python()
print(type(InstanceOfPython))
Output:
<class 'list'>
<class 'dict'>
<class '__main__.Python'>
Python vars function
The vars function in Python provides the dict attribute associated with the specified object.
Python vars Function Example
To demonstrate the functionality of the vars function in Python, let us consider a specific example.
class Python:
def __init__(self, x = 7, y = 9):
self.x = x
self.y = y
InstanceOfPython = Python()
print(vars(InstanceOfPython))
Output:
{'y': 9, 'x': 7}
Python zip Function
The zip function in Python produces a zip object that aligns the corresponding indices of several containers. It accepts zero or more iterable arguments, transforms them into an iterator that consolidates elements according to the provided iterables, and yields an iterator composed of tuples.
Python zip Function Example
To demonstrate the functionality of the zip function in Python, we can consider a specific example.
numList = [4,5, 6]
strList = ['four', 'five', 'six']
# No iterables are passed
result = zip()
# Converting itertor to list
resultList = list(result)
print(resultList)
# Two iterables are passed
result = zip(numList, strList)
# Converting itertor to set
resultSet = set(result)
print(resultSet)
Output:
[]
{(5, 'five'), (4, 'four'), (6, 'six')}
Total Number of Built-in Functions in Python
Python offers a diverse array of built-in functions. In the most recent release, version 3.11, Python includes over 70 built-in functions.
We can explore all the built-in functions that Python offers by utilizing the code below:
Python Example to Find Total Number of Built-in Functions
To demonstrate how to determine the total count of built-in functions available in Python, let's consider an example.
import builtins
print(dir(builtins))
Output:
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BaseExceptionGroup', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception', 'ExceptionGroup', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__IPYTHON__', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'display', 'divmod', 'enumerate', 'eval', 'exec', 'execfile', 'filter', 'float', 'format', 'frozenset', 'get_iPython', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'repr', 'reversed', 'round', 'runfile', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
Conclusion
In this tutorial, we explored the comprehensive topic of Python Built-in Functions. We examined a variety of built-in functions available in Python, including abs, bin, all, bool, compile, sum, ascii, float, among others. Built-in functions in Python are characterized as those whose functionalities are inherently defined within the language. The Python interpreter provides a collection of functions that are consistently available for developers to utilize. We delved into each of these functions thoroughly, accompanied by practical examples and their corresponding outputs. To summarize, the realm of Python built-in functions is extensive and plays a crucial role in facilitating efficient and time-effective coding practices.
Python Built-in Functions FAQs
1. What are Python's built-in functions?
The functions that are integrated within Python are known as built-in functions, which come with pre-defined capabilities. The Python interpreter includes a variety of functions that are consistently available for utilization. Among the numerous built-in functions in Python, you will find examples such as abs, bin, all, bool, compile, sum, ascii, and float, among others.
2. How many built-in functions are there in Python?
In Python 3.11, the language includes over 70 built-in functions. To view this list, we can utilize the following method:
import builtins
print(dir(builtins))
3. What is the difference between built-in functions and user-defined functions?
In Python, built-in functions are pre-defined functions that come with the language itself. Examples of such functions include print and len.
Whereas,
User-defined functions: In Python, user-defined functions are established by users or developers through the utilization of the def keyword.
4. What are the commonly used built-in functions in Python?
There are various built-in functions in Python, but let's have a look at some commonly used:
- print: This function displays output
- len: This helps in finding the length
- max, min: Largest/smallest value
- sum: Produces the Sum of elements
- sorted: It sorts the sequence
- type: It returns the type of object
- range: The range function generates the sequence of numbers
5. How do abs, round, and pow work?
The abs function, referred to as the Absolute function, transforms integers into their positive equivalents. For instance: abs(-5) results in 5.
The round function is utilized to round floating-point numbers. It takes two parameters: the value to be rounded and the step value, which specifies the number of decimal places to which the number will be rounded. For instance: round(4.567, 2) results in --> 4.57.
The pow function is made up of two elements: the base and the exponent, which are utilized to compute the result of raising a base number to the specified exponent. For instance: pow(2, 3) yields --> 8