Updated July 24, 2023
Introduction to Python Built-in Functions
Built-in functions are pre-defined in the programming language’s library for the programming to directly call the functions wherever required in the program for achieving certain functional operations. A few of the frequently used built-in functions in Python programs are abs(x) for fetching the absolute value of x, bin() for getting the binary value, bool() for retrieving the boolean value of an object, list() for lists, len() to get the length of the value, open() to open the files, pow() for returning the power of a number, sum() for fetching the sum of the elements, reversed() for reversing the order, etc.
Examples of Python built-in functions
Here are the examples of python built-in functions mentioned below
1. abs(x)
Returns the absolute value of a number. In case a complex number is passed, the magnitude of that number is returned. It is the same as the distance from the origin of a point on an x-y graph. For e.g.-
Abs(-3) =3
abs(3+4i) = 5
Code:
a = 12
b = -4
c = 3+4j
d = 7.90
print(abs(a))
print(abs(b))
print(abs(c))
print(abs(d))
Output:
2. all(x)
Same as logical ‘and’ operator. That means it will return true if all variables in the iterator are true. Here iterable objects are referred to as tuple, lists, dictionary.
A variable is said to be true in python if it is non-zero and not NONE. Here NONE is a keyword defined in python that is considered null.
For eg=, if the iterable ‘item’ contains value ‘2,4,5,6,1’ – The result will be true.
If item1= ‘2,0,4,5’ – The result will be false
Code:
tuple = (0, True, False)
x = all(tuple)
print(x)
output:
Explanation – Here, all() returns False because the first and third value in the tuple is false.
Code:
sampledict = {0 : "Apple", 1 : "Orange"}
x = all(sampledict)
print(x)
output:
Explanation- Here, all() returns False because one of the keys is false, and in the case of dictionaries, only the keys are checked, not the values.
3. any(x)
This function is the same as the logical ‘OR’ operator that returns False only if all the variables present in an iterable are false. Here iterable refers to the tuple, dictionary, and lists.
Note- For an empty iterable object, any() returns False.
For example- any(2,3,4,5,9) – True
Any(2,0,9,1,8) – Returns False
Code:
myset = {0, 1, 0}
x = any(myset)
print(x)
Output:
Explanation- In the above program, any function returns True, and the set is given is having at least one True value.
4. bin()
This function returns the binary value of a number.
Code:
a=5
print(bin(a))
Output:
5. round()
It gives a roundoff value for a number, i.e. gives, the nearest integer value for a number. This function accepts one argument, either decimal, float, or integer, and gives roundoff output.
Code:
print(round(4.5))
print(round(-7.7))
Output:
6. bin()
It returns the binary value for the number passed in the argument. The only integer can be passed as an argument to the function.
Code:
print(bin(4))
print(bin(9))
Output:
7. bool()
This function returns the Boolean value of an object.
Code:
print(bool(0))
print(bool(-4.5))
print(bool(None))
print(bool("False"))
Output:
8. bytearray()
This function returns a new array of bytes, i.e. a mutable sequence of integers from range 0 to 256.
Syntax –
bytearray(source,encoding,errors)
Note-
- The values to function are optional.
- If any non-ascii value is given to the function, it gives the error -TypeError: string argument without an encoding.
Code:
print(bytearray())
print(bytearray('Python','utf-8'))
Output:
9. compile()
It is used to generate a Python code object from a string or an AST object.
Following is the syntax for the function –
Compile(source,filename,mode,flags=0,dont_inherit=False,optimize=-1)
This function’s output is given as an argument to evaluate the () and exec() functions.
Code:
myCode = 'a = 7\nb=9\nresult=a*b\nprint("result =",result)'
codeObject = compile(myCode, 'resultstring', 'exec')
exec(codeObject)
Output:
10. list()
This function is used to convert an object to a list object.
Syntax –
list([iterable])
Here iterable refers to any sequence such as string, tuples, and iterable object or collection object such as a set or dictionary.
A mutable sequence of the list of elements is returned as an output of this function.
Code:
print(list()) #returns empty list
stringobj = 'PALINDROME'
print(list(stringobj))
tupleobj = ('a', 'e', 'i', 'o', 'u')
print(list(tupleobj))
listobj = ['1', '2', '3', 'o', '10u']
print(list(listobj))
Output:
11. len()
This function gives the length of the object as an output.
Syntax –
len([object])
Here objects must be either a sequence or a collection.
Note- The interpreter throws an error in case it encounters no argument given to the function.
Code:
stringobj = 'PALINDROME'
print(len(stringobj))
tupleobj = ('a', 'e', 'i', 'o', 'u')
print(len(tupleobj))
listobj = ['1', '2', '3', 'o', '10u']
print(len(listobj))
Output:
12. max()
This function returns the largest number in the given iterable object or the maximum of two or more numbers given as arguments.
Syntax –
max(iterable) or max(num1,num2…)
Here iterable can be a list, tuple, dictionary, or any sequence or collection.
Code:
num = [11, 13, 12, 15, 14]
print('Maximum is:', max(num))
Output:
Note- In case no arguments are given to the function, then ValueError is thrown by the interpreter.
13. min()
This function returns the minimum value from the collection object or the values defined as arguments.
Syntax –
min([iterable])
Code:
print(min(2,5,3,1,0,99))
sampleObj = ['B','a','t','A']
print(min(sampleObj))
Output:
Note– In case no arguments are given to the function, then ValueError is thrown by the interpreter.
14. map()
This function helps to debug as it provides the result after an operation is applied to each item in an iterable object.
Syntax –
map(fun,[Iterable])
where iterable can be a list, tuple, etc…
Code:
numList = (11, 21, 13, 41)
res = map(lambda x: x + x, numList)
print(list(res))
Output:
15. open()
After opening a particular file, this function returns a file object that helps to read or write into that file.
Syntax –
open(file, mode)
file -refers to the name with the complete path of the file to read or written into.\
mode- refers to the manner or the work we need to perform with the file. It can value like ‘r’,’ a’,’x’ etc.
Code:
f = open("myFile.txt", "r")#read mode
print(f.read())
Output:
16. pow()
This function returns the value of the power of 1 number to another number.
Syntax –
pow(num1,num2)
where num1, and num2 must be an integer, float, or double.
Code:
print(pow(2,-3))
print(pow(2,4.5))
print(pow(3,0))
Output:
17. oct()
This function helps to generate the octal representation of a number.
Syntax –
oct(number)
where the number can be an integer, hexadecimal, or binary number.
Code:
print("The octal representation of 32 is " + oct(32))
print("The octal representation of the"
" ascii value of 'A' is " + oct(ord('A')))
print("The octal representation of the binary" " of 32 is " + oct(100000))
print("The octal representation of the binary"
" of 23 is " + oct(0x17))
Output:
18. sorted()
This function has made the sorting of numbers very easy.
Syntax –
sorted(iterable,key,reverse)
Here, iterable – refers to the list, tuple or any collection of objects that needs to be sorted.
Key – refers to the key on which the values must be sorted.
Reverse- this can be set to true to generate the list in descending order.
The output of this function is always a list.
Code:
sampleObj = (3,6,8,2,5,8,10)
print(sorted(sampleObj,reverse=True))
sampledict = {'a':'sss','g':'wq','t':2}
print(sorted(sampledict,key= len))
Output:
19. sum()
This function helps to sum the member of an iterable object.
Syntax –
sum([iterable],start)
Iterable refers to any iterable object list, tuple, dictionary, or sequence of numbers.
Start – this marks the initialization of the sum result that needs to be added to the final result. It is an optional argument.
Code:
num = [2.5, 3, 4, -5]
numSum = sum(num)
print(numSum)
numSum = sum(num, 20)
print(numSum)
Output:
20. str()
This function helps to generate the printable representation of an Object.
Syntax –
str(object,encoding,errors)
where encoding and errors are optional.
Code:
print(str('A1323'))
b = bytes('pythön', encoding='utf-8')
print(str(b, encoding='ascii', errors='ignore'))
#errors='ignore' helps interpreter to ignore when it found a non Ascii character
Output:
21. type()
This function is used to print the type or the class the object passed as an argument belongs to. This function is used for debugging purposes.
Syntax –
type(Object)
It is also sometimes used to create a new object
Syntax-
type(name,bases,dict)
Code :
tupleObj=(3,4,6,7,9)
print(type(tupleObj))
new1 = type('New', (object, ),
dict(var1 ='LetsLearn', b = 2029))
print(type(new1))
Output :
22. callable()
This function returns True if the object passed as an argument is callable.
Syntax –
callable(Object)
Code:
def myFun():
return 5
res = myFun
print(callable(res)) #function is called to get this value
num1 = 15 * 5
print(callable(num1))#no function is called
Output:
23. input()
This function helps python to take input from the user. In python 2.7, Its name is raw_input() which has been changed to input(). Once enter or esc is pressed system is resumed again.
Syntax –
input()
24. range()
This function returns the series of numbers between 2 specific numbers. This is very useful while dealing with a loop in a program as it helps to run a loop in a specific number of times. In python 3.6 – xrange() has been renamed as the range().
Syntax –
range(start,stop,step)
Here, start- an Integer that marks the start of the series.
A stop-an integer that marks the last number of the series. The last number in the range is stop-1.
Step – an integer that lets to increment the loop with a specific number. By default, it is +1.
Code:
res = 1
for i in range(1, 10,2):
res = res * i
print("multiplication of first 10 natural number :", res)
Output:
Note- Float numbers as an argument throws an error.
25. reversed()
This function returns an iterator to access the collection in reverse order.
Syntax–
reversed([sequence] or [collection])
Code:
tupleObj=(3,4,6,7,9)
for i in reversed(tupleObj):
print(i,end=' ')
Output:
Conclusion
Python has a vast library that contains many functions, and these are defined only to ease down the work of a developer. These functions are known as built-in functions. They must be used in the way they are defined and are not advised to be overridden as it can cause side effects to the working and can lead to wrong output.
Recommended Articles
This is a guide to Python Built-in Functions. Here we discuss the basic concept, and examples of Python Built-in Functions with the codes and outputs. You may also look at the following article –