Built-in Functions in Python

FREE Online Courses: Elevate Skills, Zero Cost. Enroll Now!

One of the reasons for which Python is preferred over the other languages is the huge collection of built-in functions. You would have come across some of these like print(), int(), etc.

In this article, we will discuss these built-in functions in Python with examples. So, let us begin.

Introduction to Built-in Functions in Python

Functions are the set of lines of code that work and behave together under a name. Built-in functions are the ones whose functionality is predefined.

These get stored in the interpreter and come into action when they are called. These can be accessed from any part of the program. The Python 3.6 version has 69 built-in functions and these are:

Table of built-in functions in Python:

abs() enumerate() iter() reversed()
all() eval() len() round()
any() exec() list() set()
ascii() filter() locals() setattr()
bin() float() map() slice()
bool() format() max() sorted()
breakpoint() frozenset() memoryview() staticmethod()
bytearray() getattr() min() str()
bytes() globals() next() sum()
callable() hasattr() object() super()
chr() hash() oct() tuple()
classmethod() help() open() type()
compile() hex() ord() vars()
complex() id() pow() zip()
delattr() input() print() __import__()
dict() int() property()
dir() isinstance() range()
divmod() issubclass() repr()

abs()

This function takes the input of a number and gives the absolute value of it. That is, if the number is positive it returns the same number and if the number is negative it gives the positive part of it. For example,

Example of abs() function:

abs(4)

abs(-5.6)

Output:

4

5.6

all()

This is a function that takes a sequence as an input and checks the elements. If any of the elements is empty/ zero/ False, then it gives the output as False. Or else, it gives True. For example,

Example of all() function:

all([1,'t',7.9,[4,5]])

all({4,'','y'})

Output:

True

False

any()

The function any() also takes a sequence as an input and checks its elements. It gives False only if all the values of the container are empty/ zero/ False. Even if there is one nonzero/nonempty True value, it returns True. For example,

Example of any() function:

any(('t',7,9,'',False))

any(['',False,0])

Output:

True

False

ascii()

This function returns the printable form of any object passed as an argument. If we give any non-ascii character, then the interpreter adds a backslash(\) and escapes it using another backslash(\). For example,

Example of ascii() function:

ascii('r')

ascii('\t')

ascii('Hello \n world!')

ascii([3,'/'])

Output:

“‘r'”

“‘\\t'”

“‘Hello \\n world!'”

“[3, ‘/’]”

We can see that the characters \t and \n got escaped as they are non-ascii characters. And when we pass a list, then each value’s ASCII value is returned as a list.

bin()

This function converts the integer value given as an input into a binary number. IF we give a non-integer value, then we get an error. For example,

Example of bin() function:

bin(9)

bin(-3)

bin(5.7)

bin('u')

Output:

‘0b1001’

‘-0b11’

Traceback (most recent call last):
File “<pyshell#15>”, line 1, in <module>
bin(5.7)
TypeError: ‘float’ object cannot be interpreted as an integer

Traceback (most recent call last):
File “<pyshell#16>”, line 1, in <module>
bin(‘u’)
TypeError: ‘str’ object cannot be interpreted as an integer

bool()

This function takes a value as an argument and returns either True or False. It gives True if the value is not empty/zero/False. Or else it returns False. For example,

Example of bool() function:

bool(7)

bool([])

bool(False)

Output:

True

False

False

bytearray()

It takes an integer as an argument and returns an array of integers between 0 to 256. The array returned will be of the byte size of the argument. We can do the operations that we do on a list on this returned array. For example,

Example of bytearray() function:

arr=bytearray(6)

arr

arr[3]

for i in arr: print(i)


arr[4]=56
arr[5]=1

arr.append(19)

print('The array after modification is:')
for i in arr: print(i)

Output:

bytearray(b’\x00\x00\x00\x00\x00\x00′)

0
0
0
0
0
0

The array after modification is:
0
0
0
0
56
1
19

It can also take a sequence as an input and it encodes the values in the sequence as shown below.

Example of bytearray() function with sequences as arguments:

bytearray([1,2,3,4,5])

bytearray('aeiou','utf-8')

Output:

bytearray(b’\x01\x02\x03\x04\x05′)

bytearray(b’aeiou’)

breakpoint()

This function is used for the debugging process and is introduced in Python 3.7 version. It can be used as an alternative for the pdb module. Using pdb, when we debug using a debugger and again if we want to debug using another debugger. Then we had to remove the code related to the previous debugger.

This function solves this problem of tight coupling between the actual and the debugging code. For example,

Example of breakpoint() function:

message='Hello'
breakpoint()
print(message)

Output:

–Return–
None
> <ipython-input-1-ce49f3863458>(2)<module>()
1 message=’Hello’
—-> 2 breakpoint()
3 print(message)ipdb> message
‘Hello’ipdb>

bytes()

This function returns a byte object similar to the bytearray(), but the object returned by this function is immutable. For example,

Example of bytes() function:

obj=bytes(5)
obj

obj[3]=5

bytes([1,2,3])

bytes('PythonGeeks','utf-8')

Output:

b’\x00\x00\x00\x00\x00′

Traceback (most recent call last):
File “<pyshell#3>”, line 1, in <module>
obj[3]=5
TypeError: ‘bytes’ object does not support item assignment

b’\x01\x02\x03′

b’PythonGeeks’

callable()

Callable takes an object as an argument and returns either True or False, based on whether the object is callable or not. User-defined functions and built-in functions are callable. For example,

Example of callable() function:

callable(1)

callable(callable)

callable([1,2,3])

Output:

False

True

False

chr()

This function takes the Unicode value as an input and returns the respective character. For example,

Example of chr() function:

chr(45)

chr(66)

Output:

‘-‘

‘B’

classmethod()

This method returns the class method taking the input as the functions inside a class. This helps us call the method in the way we call any other function.

Example of classmethod() function:

class MyClass():
    def func(self):
    print("Welcome to PythonGeeks!")

MyClass.func=classmethod(MyClass.func)
MyClass.func()

Output:

Welcome to PythonGeeks!

compile()

This method returns the code object of the code given as an input in the form of a string. For example,

Example of compile() function:

exec(compile('x=4\ny=6\nprint(x*y)','','exec'))

Output:

24

The first argument is the code in the form of a string. The second argument is the file name from which the code is to be read. Here, we do not need any filename. So, no argument needs to be specified.

The third argument is the mode given as a string. Here we need to execute, so it is ‘exec’. The compile() returns the object representing this code and we use the exec() function to get the output.

complex()

This function is used to convert the number given as an input into a complex value. For example,

Example of complex() function:

complex(3)

complex(0.5)

complex(4,3.2)

complex(2+6j)

Output:

(3+0j)

(0.5+0j)

(4+3.2j)

(2+6j)

delattr()

This function deletes the attribute of an object. It takes two inputs, the object containing the attribute and the attribute.

Example of delattr() function:

class Greet():
    a='Hi'
    b='Hello'

greeting=Greet()

greeting.a

delattr(Greet,'a')
greeting.a

greeting.b

Output:

‘Hi’

Traceback (most recent call last):
File “<pyshell#39>”, line 1, in <module>
greeting.a
AttributeError: ‘Greet’ object has no attribute ‘a’

‘Hello’

dict()

This function converts the input into the dictionary data type and returns it. For example,

Example of dict() function:

dict()


dict([('a','e'),(1,2)])

dict(a=4,b=5)

Output:

{}

{‘a’: ‘e’, 1: 2}

{‘a’: 4, ‘b’: 5}

dir()

This function takes an object and returns the list of all the methods that can be applied to that object, called the attributes.

Example of dir() function:

a=5

dir(a)

dir([1,2,5]) 

Output:

[‘__abs__’, ‘__add__’, ‘__and__’, ‘__bool__’, ‘__ceil__’, ‘__class__’, ‘__delattr__’, ‘__dir__’, ‘__divmod__’, ‘__doc__’, ‘__eq__’, ‘__float__’, ‘__floor__’, ‘__floordiv__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getnewargs__’, ‘__gt__’, ‘__hash__’, ‘__index__’, ‘__init__’, ‘__init_subclass__’, ‘__int__’, ‘__invert__’, ‘__le__’, ‘__lshift__’, ‘__lt__’, ‘__mod__’, ‘__mul__’, ‘__ne__’, ‘__neg__’, ‘__new__’, ‘__or__’, ‘__pos__’, ‘__pow__’, ‘__radd__’, ‘__rand__’, ‘__rdivmod__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__rfloordiv__’, ‘__rlshift__’, ‘__rmod__’, ‘__rmul__’, ‘__ror__’, ‘__round__’, ‘__rpow__’, ‘__rrshift__’, ‘__rshift__’, ‘__rsub__’, ‘__rtruediv__’, ‘__rxor__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__sub__’, ‘__subclasshook__’, ‘__truediv__’, ‘__trunc__’, ‘__xor__’, ‘as_integer_ratio’, ‘bit_length’, ‘conjugate’, ‘denominator’, ‘from_bytes’, ‘imag’, ‘numerator’, ‘real’, ‘to_bytes’]

[‘__add__’, ‘__class__’, ‘__class_getitem__’, ‘__contains__’, ‘__delattr__’, ‘__delitem__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__gt__’, ‘__hash__’, ‘__iadd__’, ‘__imul__’, ‘__init__’, ‘__init_subclass__’, ‘__iter__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__mul__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__reversed__’, ‘__rmul__’, ‘__setattr__’, ‘__setitem__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘append’, ‘clear’, ‘copy’, ‘count’, ‘extend’, ‘index’, ‘insert’, ‘pop’, ‘remove’, ‘reverse’, ‘sort’]

divmod()

This takes two integers of float values as arguments. It returns a tuple containing a quotient and remainder obtained by dividing the first value by the second one.

Example of divmod() function:

divmod(9,3)

divmod(19,5)

Output:

(3, 0)

(3, 4)

enumerate()

This function takes an iterable and returns the enumerated object for that iterable. It adds a counter by looping through the iterable.

Example of enumerate() function:

for i in enumerate(['Python','C++','Java','C']):
    print(i)

Output:

(0, ‘Python’)
(1, ‘C++’)
(2, ‘Java’)
(3, ‘C’)

eval()

This function takes an expression in the form of a string, evaluates it, and returns the result.

Example of eval() function:

eval('3+4*2')

a=10
eval('4+a//6')

Output:

11

5

exec()

This function is used to execute the code dynamically. It takes the code in the form of a string as an input and returns the result on running it.

Example of eval() function:

exec('print("Hello")')

exec('x=2;y=9;print(y/x)')

Output:

Hello

4.5

filter()

This function is used along with the lambda(). This checks the condition for every element of the iterable and adds only those values that satisfy the condition.

Example of filter() function:

list(filter(lambda i:i%2,range(10)))

Output:

[1, 3, 5, 7, 9]

float()

This function is used to convert the integers or appropriate strings with numeric characters into float values. If we give strings or other data types that are not compatible, that cannot be converted into the float, then we get an error.

Example of float() function:

float(12)

float('6')

float('y')

Output:

12.0

6.0

Traceback (most recent call last):
File “<pyshell#2>”, line 1, in <module>
float(‘y’)
ValueError: could not convert string to float: ‘y’

format()

You would have seen this in strings like the function that is used for combining the constant strings and the variables. The below example shows this.

Example of str.format() function:

name='abc'
age=15

print('{} is {} years old!'.format(name,age))

print('{1} is {0} years old!'.format(age,name))

print('{nm} is {ag} years old!'.format(nm=name,ag=age))

Output:

abc is 15 years old!

abc is 15 years old!

abc is 15 years old!

Besides this, there is another built-in format() function that takes two arguments. The first one is a value and the second one is a format specifier. It returns the value converted in the specified format.

Example of format() method:

format(19,'b')

format(3.52345,'1.4f')

Output:

‘10011’

‘3.5234’

frozenset()

This is another data type conversion function that converts the input iterable into a frozenset.

Example of frozenset() method:

frozenset({1,2,3,4,3})

frozenset(['a','b','v'])

frozenset((4.5,2.3,9.0))

Output:

frozenset({1, 2, 3, 4})

frozenset({‘a’, ‘b’, ‘v’})

frozenset({9.0, 2.3, 4.5})

getattr()

This function takes the object and the name of the attribute as the arguments. It returns the value of the attribute present in that object.

Example of getattr() method:

class Lang():
    language='Python'

getattr(Lang,'language’)

Output:

‘Python’

globals()

This function returns all the global objects that can be accessed in the current module or scope. This also includes the global variables that the programmer creates.

Example of globals() method:

name='PythonGeeks'

list1=['a','e','i']

globals()

Output:

{‘__name__’: ‘__main__’, ‘__doc__’: None, ‘__package__’: None, ‘__loader__’: <class ‘_frozen_importlib.BuiltinImporter’>, ‘__spec__’: None, ‘__annotations__’: {}, ‘__builtins__’: <module ‘builtins’ (built-in)>, ‘name’: ‘PythonGeeks’, ‘list1’: [‘a’, ‘e’, ‘i’]}

hasattr()

This function returns either True or False by checking if the specified object has the given argument.

Example of hasattr() method:

class Numbers():
    nos=list(range(10))

  
hasattr(Numbers,'nos')

hasattr(Numbers,'numbers')

Output:

True

False

hash()

In Python, the hashable objects are mapped to the integer values using the hash function. This function returns the respective hash value of the specified object. We get an error if the argument is not a hashable object.

Example of hash() method:

hash(45)

hash('Python')

hash(True)

hash(5.6)

hash([1,3])

Output:

45

-1365025006759820311

1

1383505805528215557

Traceback (most recent call last):
File “<pyshell#12>”, line 1, in <module>
hash([1,3])
TypeError: unhashable type: ‘list’

help()

This function is a friend to all the programmers! It gives details about any module, object, method, keywords, and symbols.

Example of help() method:

help(print)

Output:

Help on built-in function print in module builtins:

print(…)
print(value, …, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

hex()

This function takes an integer as an input and returns the hexadecimal form of the value.

Example of hex() method:

hex(6)

hex(45)

hex(-19)

Output:

‘0x6’

‘0x2d’

‘-0x13’

id()

This function takes an object as an input and returns the identity, a unique and constant number assigned to each object.

Example of id() method:

var=42

id(var)

id(42)==id(var)

Output:

1617920683600

True

input()

There are many cases where we need to take input(s) from the users to move forward in the program. We can do this by using this function. It returns the user’s input in the form of a string. We can use the data type conversion functions to get the value in the desired format.

Example of input() method:

num=input("Enter a number: ")

num

num=int(input("Enter a new number: "))

num

Output:

Enter a number: 23

’23’

Enter a new number: 12

12

int()

This function takes an integer, float, or a numeric string and converts it into an integer. If we give any incompatible argument, we get an error.

Example of int() method:

int(5.6)

int('3')

int([1,3])

Output:

5

3

Traceback (most recent call last):
File “<pyshell#29>”, line 1, in <module>
int([1,3])
TypeError: int() argument must be a string, a bytes-like object or a number, not ‘list’

isinstance()

This function takes an object and a class as arguments. It returns either True or False by checking if the object belongs to the specified class or not.

Example of isinstance() method:

isinstance(3,int)

isinstance((1,2),list)

Output:

True

False

issubclass()

This function takes two classes as inputs. It checks if the first class is the subclass of the second one and based on this it gives a boolean value. For example,

Example of issubclass() method:

class Numbers():
    list1=[1,2,3,4,5]

  
class OddNos(Numbers):
    list2=[1,3,5]

  
issubclass(OddNos,Numbers)

issubclass(Numbers,OddNos)

issubclass(Numbers,Numbers)

Output:

True

False

True

iter()

This function is mainly used in the for loops to iterate over the object. This function takes an object and returns an iterator object corresponding to the argument. For example,
Example of iter() method:

for x in iter({2,4,6,8}):
    print(x)

Output:

8
2
4
6

len()

This function takes the sequence (list, tuple, string, etc.) or a collection (dictionary, set, etc.) as an input and returns the length of the sequence. For example,
Example of len() method:

len([0,1,2,3,4,5])

len('Python Geeks')

len({1:1,2:4,5:25})

Output:

6

12

3

list()

This function takes an iterable object as an input and converts it into a list.

Example of list() method:

list('Python')

list({1,2,3,4,5})

list(('a','b',5.6,3))

Output:

[‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]

[1, 2, 3, 4, 5]

[‘a’, ‘b’, 5.6, 3]

locals()

This function returns a directory of local objects in the current module or file.

Example of locals() method:

a=3
def func():
    b=0

locals()

Output:

{‘__name__’: ‘__main__’, ‘__doc__’: None, ‘__package__’: None, ‘__loader__’: <class ‘_frozen_importlib.BuiltinImporter’>, ‘__spec__’: None, ‘__annotations__’: {}, ‘__builtins__’: <module ‘builtins’ (built-in)>, ‘a’: 3, ‘func’: <function func at 0x00000181C201F280>}

map()

This function is generally used along with the lambda function. This maps each element of the iterable to the function and returns the modified iterable.

Example of map() method:

list(map(lambda i: i*2,['a','b','c']))

Output:

[‘aa’, ‘bb’, ‘cc’]

max()

This function takes a container or iterable containing values of similar data types as an argument. It returns the value of the largest element. If the sequence or the container contains elements that cannot be compared, then it gives an error.

Example of max() method:

max([-4,5.4,19,-23,7.9])

max({'a','b','y','i'})

max([1,2,3,'t','i'])

Output:

19

‘y’

Traceback (most recent call last):
File “<pyshell#10>”, line 1, in <module>
max([1,2,3,’t’,’i’])
TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’

memoryview()

This function takes a bytes-like object as an argument and returns the memory view of the object.

Example of memoryview() method:

b=bytes(14)

memoryview(b)

Output:

<memory at 0x00000181C4129580>

min()

This function takes a container or iterable containing values of similar data types as input. It returns the value of the smallest element. If the sequence or the container contains elements that cannot be compared, then it gives an error.

Example of min() method:

min(['c','y','o','r'])

min({3,4,5,-2,-9})

min({'5',8,0.9,'t'})

Output:

‘c’

‘y’

Traceback (most recent call last):
File “<pyshell#18>”, line 1, in <module>
min({‘5′,8,0.9,’t’})
TypeError: ‘<‘ not supported between instances of ‘str’ and ‘float’

next()

This function takes an iterator and returns the next element in the input. If we call it again, it remembers the value it returned previously and outputs the next value.

Example of next() method:

iterator=iter(['a','t','i','p'])

next(iterator)

next(iterator)

next(iterator)

next(iterator)

next(iterator)

Output:

‘a’

‘t’

‘i’

‘p’

Traceback (most recent call last):
File “<pyshell#32>”, line 1, in <module>
next(iterator)
StopIteration

object()

It does not take any arguments but returns as a featureless object. The object returned will have all the methods common to the Python objects.

Example of object() method:

obj=object()

print(obj,type(obj))

dir(obj)

Output:

<object object at 0x00000181C414B470> <class ‘object’>

[‘__class__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’]

oct()

This function takes an integer as an input and returns its octal form. It gives an error if any value of another data type is given as an argument.

Example of oct() method:

oct(19)


oct(-5)


oct(5.6)

Output:

‘0o23’

‘-0o5’

Traceback (most recent call last):
File “<pyshell#38>”, line 1, in <module>
oct(5.6)
TypeError: ‘float’ object cannot be interpreted as an integer

open()

This function is used for file management. It takes two arguments. The first one is the path where the required file exists, by default it checks in the current directory, The second argument is the mode, which could be ‘r’ to read, ‘w’ to write, ‘a’ to append, etc.

Example of open() method:

file=open('F:\\c\\Documents\\python.txt')

print(file)

print(file.read())

Output:

<_io.TextIOWrapper name=’F:\\c\\Documents\\python.txt’ mode=’r’ encoding=’cp1252′>

Python is fun!

ord()

This function does the opposite of the function chr(). It takes a Unicode character as an input and returns the corresponding integer representation.

Example of ord() method:

ord('4')

ord('z')

ord('?')

Output:

52

122

63

pow()

The function pow() takes two inputs, the base, and the exponential. And it returns the power of the first one to the second number.

Example of pow() method:

pow(5,3)

pow(-2,4)

pow(0.9,5)

pow(2,-1)

pow(4,0.9)

Output:

125

16

0.5904900000000001

0.5

3.4822022531844965

print()

This would be the most familiar function to you! It takes objects separated by commas and displays them by giving space between them. It adds a new line at the end.

We can change the default space displayed between the objects to any other character by giving an argument named ‘sep’. We can also change the newline being added at the end to another character by specifying the argument ‘end’. For example,

Example of print() method:

print('Hello')

print('a','e','i','o','u',sep=',')

print('PythonGeeks',end='.'); print('This is the continuation')

Output:

Hello

a,e,i,o,u

PythonGeeks.This is the continuation

property()

The property method is used to get the property attribute from the specified getter, setter, or deleter. Its syntax is:

property(fget=None, fset=None, fdel=None, doc=None)

The fget is used as a getter, fset as a setter, and fdel as a deleter. The doc is used to get the docstring.

range()

This function can take up to three arguments and the first and last ones are optional. It gives the sequence of numbers from the first argument, which is by default 0, to the second one, executing it.

If the third argument, called step, is specified it gives the numbers in the range such that the difference between them is equal to the step. For example,

Example of range() method:

list(range(5))

list(range(-2,8))

list(range(-6,9,3))

Output:

[0, 1, 2, 3, 4]

[-2, -1, 0, 1, 2, 3, 4, 5, 6, 7]

[-6, -3, 0, 3, 6]

repr()

It takes an object as an input and returns the printable form of the object. For example,

Example of repr() method:

repr('Python')

repr(9)

repr([1,2,3,4])

Output:

“‘Python'”

‘9’

‘[1, 2, 3, 4]’

reversed()

It takes a sequence as an input and returns another sequence with the elements in the reverse order of the given input sequence. It will not have any effect on the original sequence. For example,

Example of reverse() method:

list1=['a','b','c','d']

list2=reversed(list1)
list2

list(list2)

list1

Output:

<list_reverseiterator object at 0x00000181C4180F40>

[‘d’, ‘c’, ‘b’, ‘a’]

[‘a’, ‘b’, ‘c’, ‘d’]

round()

This function takes two arguments, on which the second one is optional. It rounds the given number to the specified number of decimal digits. If the number of decimal digits is not specified then it rounds it an integer. For example,

Example of round() method:

round(1.9)

round(5.2)

round(2.39450383,4)

Output:

2

5

2.3945

set()

This function takes an iterable as input and converts it into a set. For example,

Example of set() method:

set([3,'t',6.7])

set((1,4,'y'))

Output:

{3, ‘t’, 6.7}

{1, ‘y’, 4}

setattr()

Similar to the function getattr(), setattr() also takes an attribute of an object and assigns the specified value to that attribute. It takes three arguments, object, attributes name, and value. For example,

Example of setattr() method:

class Greet():
    var='Hi'

greeting=Greet()

setattr(greeting,'var','Hello')

greeting.var

Output:

‘Hello’

slice()

This function is similar to the range and it can also take three arguments. This function returns a slice object that can be used with the iterables to get the specified index values. For example,

Example of slice() method:

slc1=slice(4)
slc2=slice(1,5,2)

'PyhtonGeeks'[slc1]

[1,2,3,4,5,6,7][slc2]

Output:

‘Pyht’

[2, 4]

sorted()

This function takes an iterable and returns the sorted version of the elements of the iterable. It does not affect the original iterable. We can also change the order from increasing to decreasing by setting the ‘reverse’ argument, which is False by default, to TrueFor example,

Example of sorted() method:

list1=[1,3.4,-3,8]

sorted(list1)

sorted(list1,reverse=True)

list1

Output:

[-3, 1, 3.4, 8]

[8, 3.4, 1, -3]

[1, 3.4, -3, 8]

staticmethod()

This function is used to convert a normal method in a class into a static method. The static methods are the ones that can be called without creating the instance of a class. For example,

Example of staticmethod() method:

class MyClass():
    def func():
        print('hello')

MyClass.func=staticmethod(MyClass.func)

MyClass.func()

Output:

hello

This function can also be used as a decorator. For example,

Example of staticmethod() as a decorator:

class MyClass():
    @staticmethod
    def func():
        print('hello')

    
MyClass.func()

Output:

hello

str()

This function is a data type conversion function that takes an object and converts it into a string. For example,

Example of str() method:

str(5.6)

str([1,2,3,4])

str(True)

Output:

‘5.6’

‘[1, 2, 3, 4]’

‘True’

sum()

This function takes a container or an iterable containing numerical values only. It returns the value of the sum of all the elements. If the sequence or the container contains elements that cannot be summed, then it gives an error. For example,

Example of sum() method:

sum([1,3.4,6,-2])

sum((5,7.8,2,-1))

sum({4,5,6,-9,2})

Output:

8.4

13.8

8

super()

This function returns the proxy object that refers to the parent class. This function can be used in the child class to access the attributes and methods of the parent class. For example,

Example of super() method:

class Parent():
    def __init__(self):
        print("This is parent class.")

class Child(Parent):
    def __init__(self):
        super().__init__()    
        print("This is a child class.")

inst=Child()

Output:

This is parent class.
This is a child class.

tuple()

This function takes an iterable as input and converts it into a tuple. For example,

Example of tuple() method:

tuple('Hello')

tuple([1,3,4,6,7])

tuple({'a',5,7.7})

Output:

(‘H’, ‘e’, ‘l’, ‘l’, ‘o’)

(1, 3, 4, 6, 7)

(‘a’, 5, 7.7)

type()

This function takes an object as an input and returns the class or the data type of the object. For example,

Example of type() method:

type(True)

type(9)

type({1,2,3,4})

type((3,))

Output:

<class ‘bool’>

<class ‘int’>

<class ‘set’>

<class ‘tuple’>

vars()

This function returns a __dict__ attribute of the class, method, instance, or object specified as an argument. If no input is given, then it is the same as a locals() function. For example,

Example of vars() method:

vars(set)

Output:

mappingproxy({‘__repr__’: <slot wrapper ‘__repr__’ of ‘set’ objects>, ‘__hash__’: None, ‘__getattribute__’: <slot wrapper ‘__getattribute__’ of ‘set’ objects>, ‘__lt__’: <slot wrapper ‘__lt__’ of ‘set’ objects>, ‘__le__’: <slot wrapper ‘__le__’ of ‘set’ objects>, ‘__eq__’: <slot wrapper ‘__eq__’ of ‘set’ objects>, ‘__ne__’: <slot wrapper ‘__ne__’ of ‘set’ objects>, ‘__gt__’: <slot wrapper ‘__gt__’ of ‘set’ objects>, ‘__ge__’: <slot wrapper ‘__ge__’ of ‘set’ objects>, ‘__iter__’: <slot wrapper ‘__iter__’ of ‘set’ objects>, ‘__init__’: <slot wrapper ‘__init__’ of ‘set’ objects>, ‘__sub__’: <slot wrapper ‘__sub__’ of ‘set’ objects>, ‘__rsub__’: <slot wrapper ‘__rsub__’ of ‘set’ objects>, ‘__and__’: <slot wrapper ‘__and__’ of ‘set’ objects>, ‘__rand__’: <slot wrapper ‘__rand__’ of ‘set’ objects>, ‘__xor__’: <slot wrapper ‘__xor__’ of ‘set’ objects>, ‘__rxor__’: <slot wrapper ‘__rxor__’ of ‘set’ objects>, ‘__or__’: <slot wrapper ‘__or__’ of ‘set’ objects>, ‘__ror__’: <slot wrapper ‘__ror__’ of ‘set’ objects>, ‘__isub__’: <slot wrapper ‘__isub__’ of ‘set’ objects>, ‘__iand__’: <slot wrapper ‘__iand__’ of ‘set’ objects>, ‘__ixor__’: <slot wrapper ‘__ixor__’ of ‘set’ objects>, ‘__ior__’: <slot wrapper ‘__ior__’ of ‘set’ objects>, ‘__len__’: <slot wrapper ‘__len__’ of ‘set’ objects>, ‘__contains__’: <method ‘__contains__’ of ‘set’ objects>, ‘__new__’: <built-in method __new__ of type object at 0x00007FFACBD750F0>, ‘add’: <method ‘add’ of ‘set’ objects>, ‘clear’: <method ‘clear’ of ‘set’ objects>, ‘copy’: <method ‘copy’ of ‘set’ objects>, ‘discard’: <method ‘discard’ of ‘set’ objects>, ‘difference’: <method ‘difference’ of ‘set’ objects>, ‘difference_update’: <method ‘difference_update’ of ‘set’ objects>, ‘intersection’: <method ‘intersection’ of ‘set’ objects>, ‘intersection_update’: <method ‘intersection_update’ of ‘set’ objects>, ‘isdisjoint’: <method ‘isdisjoint’ of ‘set’ objects>, ‘issubset’: <method ‘issubset’ of ‘set’ objects>, ‘issuperset’: <method ‘issuperset’ of ‘set’ objects>, ‘pop’: <method ‘pop’ of ‘set’ objects>, ‘__reduce__’: <method ‘__reduce__’ of ‘set’ objects>, ‘remove’: <method ‘remove’ of ‘set’ objects>, ‘__sizeof__’: <method ‘__sizeof__’ of ‘set’ objects>, ‘symmetric_difference’: <method ‘symmetric_difference’ of ‘set’ objects>, ‘symmetric_difference_update’: <method ‘symmetric_difference_update’ of ‘set’ objects>, ‘union’: <method ‘union’ of ‘set’ objects>, ‘update’: <method ‘update’ of ‘set’ objects>, ‘__class_getitem__’: <method ‘__class_getitem__’ of ‘set’ objects>, ‘__doc__’: ‘set() -> new empty set object\nset(iterable) -> new set object\n\nBuild an unordered collection of unique elements.’})

zip()

This function takes iterables as an input. It returns tuples, each containing the elements of the iterables packed based on their index positions, For example,

Example of zip() method:

for i in zip([1,2,3,4],[4,5,6],[7,8,9,10,11]):
    print(i)

Output:

(1, 4, 7)
(2, 5, 8)
(3, 6, 9)

__import__()

This function is similar to the ‘import module_name’ statement that we can use as an alternative. The syntax is :

__import__(module_name, globals, locals, fromlist, level)

For example, to import the collections module we can write
Example of __import__() method:

__import__('collections', globals(), locals(), [], 0)

Interview Questions on Python Built in functions

1. Write a function that takes the input of two numbers and returns the sum of the numbers.
Ans. We can use the input() function and convert it to the integer using the int() to add them.

Example of adding two numbers by taking the input from the user:

n1=int(input('Enter the first number: '))

n2=int(input('Enter the second number: '))

print(n1+n2)

Output:

Enter the first number: 5

Enter the second number: 23

28

Q2. Divide two numbers and output the result of the quotient up to 5 decimal points.
Ans. We can use the round() function to get the output up to 5 decimal values

Example of rounding the values:

a=4/3

print(round(a,5))

Output:

1.33333

Q3. Write a function that takes the elements of a list and gives the output list with the square of the numbers of the given list.
Ans. We can use the map() function.

Example of mapping the values of a list:

list1=[1,2,3,4,5]

list2=list(map(lambda x: x**2, list1))
list2

Output:

[1, 4, 9, 16, 25]

Q4. Write a program to get the unique values of a list.
Ans. We can convert it to a set and then back to a list. Since the set holds only unique values, we get the output list as the ones with unique elements.

Example of getting unique values of a list:

list1=['e',1,5,2,'t','e']
set1=set(list1)
list2=list(set1)

list2

Output:

[1, 2, 5, ‘t’, ‘e’]

Q5. Write a function to know if a method exists in the directory of a construct.
Ans. We can use the hasattr() function.

Example of checking existence of a method for a construct:

hasattr(set,'append')

hasattr(tuple,'del')

hasattr(list,'pop')

Output:

False

False

True

Quiz on Python Built-In Functions

Conclusion

Hurray! Finally done with all the built-in functions. Hope you understood the functions and the examples. I know it is a lot to remember. But the main thing here is not remembering, but knowing that such a function exists. To know its syntax and other things, visit us again. Happy learning.

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *