Python Built-in Functions: Brief Overview

Built In Functions In Python

A built-in function is a function that is already available in a programming language. In this article, let’s understand these functions, along with examples.


abs()

abs(number)

This function returns the absolute value of a number. The parameter can be an integer, floating-point number, or complex number In the case of a complex number it returns the magnitude of the number.

print(abs(10))
print(abs(-210))
print(abs(2 + 3j))  #complex number

Output:

10
210
3.605551275463989

aiter()

aiter(async iterable)

This function returns an asynchronous iterator for asynchronous iterable. It is a new function available in python 3.10.

A sample implementation of this function. (For more examples visit here)

async def aitersync(iterable):
    results = []

    async for x in aiter(iterable):
        results.append(x)

    return iter(results)

all()

all(iterable)

This function takes iterable (Iterables are objects that can be used in an iterative way or in for loops. for example: list, string, dictionary, set, tuples, etc) as the argument and returns the true value in two cases.

  1. when all elements of the iterable are true
  2. when the iterable is empty
#Below list wil return false as all the elements are not true.
list1 = [10, 20, 30, 40, 50, false] 
print(all(list1)    

#Below set will return true as the set is empty
set1 = {}
print(all(set1))

#Below dictionary wil return true as all elements of the dictonary are true.
dict1 = {1: "Ask", 2: "Python"}
print(all(dict1))

any()

any(iterable)

This function also takes the iterable as the argument and returns true if any element of the iterable is true. It returns false in the case of an empty iterable.

#Below list wil return True even when some the elements are not true.
list1 = [10, 20, 30, 40, 50, false] 
print(all(list1)    

#Below set will return False as the set is empty
set1 = {}
print(all(set1))

ascii()

ascii(object)

This function returns a printable version of the object. In the case of none-ascii characters, it replaces them with the escape character.

x = ascii("åsk python")
print(x)

Output: ‘\xe5sk python’

The character å is replaced with the escape character.

bin()

bin(int)

This function returns the binary version of a specified integer. The return string will always start with the prefix 0b.

num = bin(7)
print(num)

Output: 0b111

bool()

bool(object)

This function returns a boolean value (True or False) for a specified object. The function will return true if the object is true, or the function will return false if the object is false, or none, or zero(0), or empty.

#below object will return False, as it is empty
list1 = bool()
print(list1)

#below object will return False, as it is 0
list2 = bool(0)
print(list2)

#below object will return True, as it is non-empty
nums = bool({1,2,3,4,5})
orint(nums)

bytearray()

bytearray(x, encoding, error)

This function returns a new array of bytes. It converts objects into bytearray objects or creates empty bytearray objects of the particular required size. It has 3 parameters

  1. x: source parameter
    • If it is an integer, the array will have that size and will be initialized with null bytes.
    • If it is a string, you must also give the encoding (and optionally, errors) parameters
  2. encoding: If the source is a string, the encoding of the string.
  3. errors: If the source is a string, the action to take when the encoding conversion fails.
arr = bytearray(5)
print(arr)

str = "Ask Python"
arr1 = bytearray(str, 'utf-8')
print(arr1)

Output:

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

bytearray(b’Ask Python’)

bytes()

byte(x, encoding, error)

This function returns a new “bytes” object. It is an immutable version of bytearray(), which means that bytes() return an object that cannot be modified. Parameters are also the same as that of bytearray()

  1. x: source parameter
    • If it is an integer, the array will have that size and will be initialized with null bytes.
    • If it is a string, you must also give the encoding (and optionally, errors) parameters
  2. encoding: If the source is a string, the encoding of the string.
  3. errors: If the source is a string, the action to take when the encoding conversion fails.
arr = bytes([1,2,3,4,5])
print(arr)

Output: b’\x01\x02\x03\x04\x05′

callable()

callable(object)

This function returns true if the object argument appears callable, False if not. If this returns True, it is still possible that a call fails, but if it is False, the calling object will never succeed.

def x():
  a = 100

print(callable(x))

Output: True

chr()

chr(int)

This function returns the character that whose Unicode is equal to that of integer int. The range of integers is 0 to 1,114,111. The function will return ValueError if the integer is out of the defined range, or TypeError if the argument is a non-integer.

num = chr(99)

print(num)

Output: c

classmethod()

#considered un-Pythonic 
classmethod(function)

#new version
@classmethod
def func(cls, args...)

This function takes a function as a parameter and transforms it into a class method. (the class method is bounded to class, not to the object, so it does not require class instances) The @classsmethod is of the decorator form for the classmethod.

Creating classmethod example:

#defining class
class Employee:
    salary = 10000
    dept: 'HR'

    def printSalary(cls):
        print('The employee earns', cls.salary, 'per month.')

#creating classmethod
Employee.printSalary = classmethod(Employee.printSalary)
Employee.printSalary()

Output: The employee earns 10000 per month

compile()

compile(source, filename, mode, flag, dont_inherit, optimize)

This function converts the source into code or AST object. The function returns SyntaxError if the compiled source is invalid and ValueError if the source contains null bytes. The parameter passed are:

  1. source: (Mandatory) The source to compile can be anything AST object, string, etc
  2. filename: (Mandatory) The name of the file from where the source was read, if no such file exits name it something yourself.
  3. mode: (Mandatory) specifies what kind of code must be compiled
    • eval – if the source contains a single expression
    • exec – if the source contains a block of statements
    • single – if the source contains a single interactive statement
  4. flag and dont_inherit: (Optional) control which compiler options should be activated and which future features should be allowed. The default value is 0 and false respectively.
  5. optimize: (Optional) specifies the optimization level of the compiler; the default value of -1

complex()

complex(real, imaginary)

This function returns for given real and imaginary values. It converts the string or number into a complex number.  If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. If any of the parameters- real or imaginary is omitted, then the default value remains 0, and the constructor serves as a numeric conversion like int and float. If both arguments are omitted, returns 0j.

z0 = complex(9,-8)
print(z0)

z1 = complex()
print(z1)

z2 = complex(10)
print(z2)

z3 = complex('10-4j')
print(z3)

z4 = complex('5-7j','7')
print(z4)

Output:

(9-8j)
0j
(10+0j)
(10-4j)
TypeError: complex() can’t take second arg if first is a string

delattr()

delattr(object, attribute)

This function deletes the named attribute, provided the object allows it. The first parameter specifies from which object the attribute is to be deleted and the second attribute specifies what has to be deleted

class Employee:
  Name= "Alex"
  Dept = "HR"
  Salary = 15000
  City = "Mumbai"

delattr(Employee, 'Salary')
#Salary attribute gets deleted from the Employee

dict()

dict(keyword arguments)
class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)

This function

This function

This function creates a new dictionary. The dict object is the dictionary class. class dict() return a new dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments.

d1 = dict(Name ="Alex", Salary =15000, City ="Mumbai")

print(d1)

Output:

{‘Name’: ‘Alex’, ‘Salary’: 15000, ‘City’: ‘Mumbai’}

dir() 

dir(object)

This function returns the list of names in the current local scope when no argument is provided. When the argument is present, then it returns a list of valid attributes for that object.

s1 = {10, 20, 30, 40,}

print(dir(s1))

Output:

[‘__and__’, ‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__iand__’, ‘__init__’, ‘__init_subclass__’, ‘__ior__’, ‘__isub__’, ‘__iter__’, ‘__ixor__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__ne__’, ‘__new__’, ‘__or__’, ‘__rand__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__ror__’, ‘__rsub__’, ‘__rxor__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__sub__’, ‘__subclasshook__’, ‘__xor__’, ‘add’, ‘clear’, ‘copy’, ‘difference’, ‘difference_update’, ‘discard’, ‘intersection’, ‘intersection_update’, ‘isdisjoint’, ‘issubset’, ‘issuperset’, ‘pop’, ‘remove’, ‘symmetric_difference’, ‘symmetric_difference_update’, ‘union’, ‘update’]

divmod()

divmod(dividend, divisor)

This function returns pair of numbers consisting of quotient and remainder for the numbers passed as parameters. It will return TypeError for the non-numeric parameters.

dividend = 110
divisor = 4
nums = divmod(dividend, divisor)

print(nums)

Output: (27, 2)

enumerate()

enumerate(iterable, start)

This function return enumerates object for iterable ( iterable must be a sequence eg- tuple). It adds a counter  (from the start which defaults to 0) to the iterable.

a = ('Monday', 'Tuesday', 'Wednesday','Thursday')
b = enumerate(a)

#notice the difference in output
print(list(a))
print(list(b))

Output:

[‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’]

[(0, ‘Monday’), (1, ‘Tuesday’), (2, ‘Wednesday’), (3, ‘Thursday’)]

eval()

eval(expression, globals, locals)

This function evaluates the expression passed as a parameter, if the expression is a valid Python statement, it will be executed. The parameters are:

  1. expression: The string/ expression to be evaluated
  2. globals(optional): must be a dictionary
  3. locals(optional): can be any mapping object.
a = 10
b = 2
c = 'print(a * a + b)'

eval(c)

Output: 102

exec()

exec(object, globals, locals)

This function doesn’t return any value, it returns None. It is a function that supports the dynamic execution of Python code. The object must be either a string or a code object. If it is a code object, then it is simply executed but in the case of a string, it is first parsed as a suite of Python statements which is then executed. Parameters are the same as eval(), except for the expression in eval() is changed with an object in exec()

filter()

filter(function, iterable)

As the name suggests, this function filters the iterable through the function to check if the item is accepted or not. It returns filtered iterable.

def Result(x):
  if x < 30:
    return False
  else:
    return True

marks = [60, 91, 12, 29, 30, 41]
pass_or_not = filter(Result, marks)

for x in pass_or_not:
  print(x)

Output: 60 91 30 41

float()

float(value)

This function returns a floating-point number constructed from a value. Value can be a number or string.

x_int = 25
y_float = float(x_int)

print(x_int)
print(y_float)

Output:

25

25.0

format()

format(value, format)

This function returns formatted values according to the specified format passed as a parameter. The default format is an empty string, however, there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language.

# binary format  - b
x = 7
print(format(x, "b"))

Output: 111

frozenset() 

frozenset(iterable)

This function returns a new set or frozenset object whose elements are taken from iterable. The elements of a set must be hashable (if it has a hash value that never changes during its lifetime). To represent sets of sets, the inner sets must be frozenset objects. If iterable is not specified, a new empty set is returned.

getattr()

getattr(object, attribute, default)

This function returns the named attribute. The first parameter specifies from which object the attribute is to be found and the second attribute specifies what (the attribute) has to be found.

class Employee:
  name = 'Alex'
  city = 'Mumbai'

Engineer = Employee()
name = getattr(Engineer, 'name')
print(name)

Output: Alex

globals()

globals()

This function returns the dictionary implementing the current module namespace. The output of global() will display all global variables and other symbols for the current program.

hasattr()

hasattr(object, attribute)

This function returns true if the specified attribute is present in the specified object, and if the attribute is not present, then it returns false.

class Employee:
  name = 'Alex'
  city = 'Mumbai'

Engineer = Employee()
x = hasattr(Engineer, 'name')
print(x)

y = hasattr(Engineer,'salary')
print(y)

Output:

True

False

hash()

hash(object)

This function returns the hash value of the object (if it has one). Hash values are integers used to quickly compare dictionary keys during a dictionary lookup.

x1 = 'Ask Python'
print('Ask Python: ', hash(x1))

x2 = 3.147
print('3.147: ',hash(x2))

x3 = 71
print('71:', hash(x3))

Output:

Ask Python: -1041620088632976012
3.147: 338958922354412547
71: 71

help()

help(object)

This function invokes the built-in help system. It is intended for interactive use. Try this function on the python shell.

  • If no argument is given, the interactive help system starts on the interpreter console.
  • If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console.
  • If the argument is any other kind of object, a help page on the object is generated.
Help1
help() with no arguments
Help2
Help() with arguments

hex()

hex(number)

This function converts the specified number into a hexadecimal value. The return string will always start with 0x.

x1 = hex(-44)
print(x1)

x2 = hex(321)
print(x2)

Output:

-0x2c

0x141

id()

id(object)

This function returns the “identity” (unique id – This is an integer that is guaranteed to be unique and constant for this object during its lifetime.) of an object.

x0 = 10
print(id(x0))

x1 = 11
print(id(x1))

x2 = x1
print(id(x2))

Output:

9756512

9756544

9756544

input()

input(prompt)

This function is used to take input from the user. The function reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

String1 = input('Input from the user: ')
print('The input:', String1)

Output:

Input from the user: Ask Python
The input: Ask Python

int()

int(value)
int (value, base)

This function returns an integer object constructed from a number or string value. If no arguments are given, then the function will return 0. The base is optional and states the number system of the value. it can be 0, 2,8,10 or 16.

#base 2 -> binary number
print(int('0b11101',2))

#base 16 -> hexadecimal number
x2 = 0xC1
print(int('0xC1',16))

Output:

29

193

isinstance()

isinstance(object, classinfo)

This function returns a boolean value. It returns true if the object parameter is an instance of the specified classinfo parameter or its subclass. Or else it returns false. The function returns TypeError if the classinfo parameter is not a type or a tuple of types.

numset = {1, 2, 3}
print('Checking for set: ', isinstance(numset, set))
print('Checking for list: ', isinstance(numset, list))

Output:

Checking for set: True
Checking for list: False

issubclass()

issubclass(class, classinfo)

The function returns a boolean value, it returns true, if the class parameter is subclass of the classinfo parameter, or else it returns false

class company:
  Office= 'AskPython'
 
class employee(company):
  name = 'Alex'
  Office = company
  
print(issubclass(employee, company))
print(issubclass(employee, employee))    #every class is its own subclass
print(issubclass(company, employee))

Output:

True

True

False

iter()

iter(object, sentinel)

This function iterator returns an object for the given object parameter until the sentinel is fetched. Sentinel is optional, it is the value used to represent the end of a sequence.

list1 = iter(["North", "East", "South", "West"])

print(next(list1))
print(next(list1))
print(next(list1))

Output:

North

East

South

len() 

len(object)

This function returns the length, that is the number of items of an object. The object parameter can be a sequence such as a string, bytes, tuple, list, or range or even a collection such as a dictionary, set, etc.

l1 = len([10,20,30,40])
print(l1)

set1 = len({1,2,3,4,5,6,7})
print(set1)

sent = len("Ask Python")
print(sent)

Output:

4

7

10

list()

list(iterable)

This function creates a list of the iterable passed as parameters. In the case of no parameter, the function will create an empty list.

string1 = 'Ask Python'
string2 = list(string1)

print(string1)
print(string2)

Output:

Ask Python
[‘A’, ‘s’, ‘k’, ‘ ‘, ‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]

locals()

locals()

This function returns a dictionary representing the current local symbol table. It also updates the local symbol table when necessary. This function doesn’t have any parameters. It returns free variables in the function block but not in the class block.

print(locals())

Output:

{‘In’: [”, ‘locals()’], ‘Out’: {}, ‘_’: ”, ‘__’: ”, ‘___’: ”, ‘__builtin__’: , ‘__builtins__’: , ‘__name__’: ‘__main__’, ‘_dh’: [‘/home/repl’], ‘_i’: ”, ‘_i1’: ‘locals()’, ‘_ih’: [”, ‘locals()’], ‘_ii’: ”, ‘_iii’: ”, ‘_oh’: {}, ‘_sh’: , ‘exit’: , ‘get_ipython’: >, ‘quit’: }

map()

map(function, iterables)

This function applies the function specified as a parameter to every item of the iterable passed as a parameter and returns the result iterators.

def solve_nums(n,m,k):
    return n*m+k

numbers = (1, 2, 3, 4)
result = map(solve_nums,(1,2,3),(10,10,10),(1,2,3))
print(result)
print(list(result))

Output:

<map object at 0x7f96078a50a0>

[11, 22, 33]

max()

max(n1, n2, n3, ...)
max(iterable)

This function returns the largest item in an iterable parameter or the largest of two or more parameters passed (n1, n2…). In the case of a string parameter, the largest item is the last item of alphabetically sorted iterable.

str1 = max("India","China", "Dubai")
print(str1)

nums = max(-2, -9, -12)
print(nums)

Output:

India

-2

memoryview()

memoryview(object)

As the name suggests the function return “memoryview” of the object; memoryview allows you to access the internal buffers of an object by creating a memory view object.

str = memoryview(b"Ask Python")

print(str)

#Unicode of the first character
print(str[0])

#Unicode of the second character
print(str[4])

Output:

<memory at 0x2ac829f42a00>

65

80

min()

min(n1, n2, n3, ...)
min(iterable)

This function returns the smallest item in an iterable parameter or the smallest of two or more parameters passed (n1, n2…). In the case of a string parameter, the smallest item is the first item of an alphabetically sorted iterable.

str1 = min("India","China", "Dubai")
print(str1)

nums = min(-2, -9, -12)
print(nums)

Output:

China

-12

next()

next(iterable, default)

This function retrieves the next item of the specified iterable. The default is optional and the value of the default is returned until the iterable has reached its end item.

nums = iter([10,20,30])

#the next element -> 1st
nums_1 = next(nums)
print(nums_1)

#the next element -> 2nd
nums_2 = next(nums)
print(nums_2)

Output:

10

20

object()

x = object()

This function doesn’t accept any parameters. It returns a new featureless object. An object has methods that are common to all instances of Python classes. It is the base for all class

abc = object()

As an output ‘abc’ object is created

oct()

oct(x)

This function converts the specified number into an octadecimal value. The return string will always start with 0o.

x1 = oct(-44)
print(x1)

x2 = oct(321)
print(x2)

Output:

-0o54
0o501

open()

open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

This function opens the file and returns a corresponding file object. The function returns OSError if the specified file is not found. The parameters are

  • File – provides the pathname, it’s a path-like object
  • mode- it is an optional string that specifies the mode in which the file is opened. The following are some commonly used modes
'r'open for reading (default)
'w'open for writing, truncating the file first
'x'open for exclusive creation, failing if the file already exists
'a'open for writing, appending to the end of the file if it exists
'b'binary mode
't'text mode (default)
'+'open for updating (reading and writing)
Modes and their description
  • buffering – It is an optional string used to set the buffering policy
  • encoding – It is an optional string used to state the encoding format
  • errors – It is an optional string used to resolve the encoding/decoding errors
  • newline – It is an optional string used to state how newlines mode work
  • closefd – It is an optional string that must be true by default; if given or else, an exception will occur.
  • opener – It is an optional string that returns an open file descriptor

ord()

ord(ch)

This function simply returns the integer representation of the Unicode code point of the parameter passed.

print(ord('T'))    
print(ord('1'))    
print(ord('@'))

Output:

84
49
64

pow()

pow(number, exponential, modulus)

This function returns a value equal to the number raised to exponential. The modulus parameter is optional, and if present the mod of number is returned.

print(pow(2,0))  
print(pow(0, 2))       
print(pow(2,3,3))     #(2*2*2)/3

Output:

1
0
2

print()

print(object(s), sep=separator, end=end, file=file, flush=flush)

This function as the name suggests prints objects to the text stream file, separated by sep and followed by end.  All other parameters except the object are optional.

nums = [1,2,3,4]

print("Numbers are: ", nums, sep='0', end='\n')
print("Ask Python")

Output:

Numbers are: 0[1, 2, 3, 4]
Ask Python

property()

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

The function takes four optional parameters and returns the property attribute.

  • fget is used for getting an attribute value. 
  • fset is used for setting an attribute value. 
  • fdel is used for deleting an attribute value.
  • doc creates a docstring for the attribute.

range()

range(start, stop, step)

This function returns an immutable sequence of numbers depending on the parameters passed. If a single parameter is passed, then the function considers it as a stop parameter.

nums = [1,2,3,4,5,6,7,8,9,10]

nums = range(5)   
print(list(nums))   

#2, and 10 are considered start and stop respectively
nums = range(2,10)    
print(list(nums))    

#increament step 2
nums = range(2,10,2) 
print(list(nums))

Output:

[0, 1, 2, 3, 4]
[2, 3, 4, 5, 6, 7, 8, 9]
[2, 4, 6, 8]

repr()

repr(object)

This function returns a string containing a printable representation of an object. In most cases, it returns the same object.

string1 = 'Ask Python'
print(repr(string1))

nums1 = [1,2,3,4]
print(repr(nums1))

Output:

‘Ask Python’
[1, 2, 3, 4]

reversed()

reversed(sequence)

This function returns the reversed order of the specified sequence parameter. Here sequence can be any indexable iterable such as list, tuple, set, etc.

list1 = [1, 2, 4, 3, 5]
print(list(reversed(list1)))

tuple1 = ('A','S','K',' ','P','Y','T','H','O','N')
print(list(reversed(tuple1)))

Output:

[5, 3, 4, 2, 1]
[‘N’, ‘O’, ‘H’, ‘T’, ‘Y’, ‘P’, ‘ ‘, ‘K’, ‘S’, ‘A’]

round()

round(number, ndigits)

This function returns a number rounded off to ndigits after the decimal point. The ndigits parameter is optional, if not provided, the function will return the nearest integer number.

print('1.8 -> ',round(1.8))
print('1.2 -> ',round(1.2))
print('1.5678 (2 decimal points)-> ',round(1.5678,2))

Output:

1 -> 1
1.8 -> 2
1.2 -> 1
1.5678 (2 decimal points)-> 1.57

set()

set(iterable)

This function constructs a set for the specified iterable parameter. If no parameters are specified, then the function will construct an empty set.

print(set())   #empty set will be constructed
print(set(('A','S','K',' ','P','Y','T','H','O','N')))
print(set(('Ask Python')))

Output:

set()
{‘S’, ‘O’, ‘K’, ‘A’, ‘H’, ‘N’, ‘P’, ‘T’, ‘Y’, ‘ ‘}
{‘t’, ‘s’, ‘A’, ‘n’, ‘P’, ‘y’, ‘o’, ‘k’, ‘ ‘, ‘h’}

setattr()

setattr(object, name, value)

This function is used either to set or modify the name and its value in the specified object parameter.

class Employee:
    name = 'Atlas'
    
emp = Employee()
print('Before:', emp.name)

#modifying the name using setattr()
setattr(emp, 'name', 'Ryle')
print('After:', emp.name)

Output:

Before: Atlas
After: Ryle

slice()

slice(stop)
slice(start, stop, step)

This function returns a slice of the object which is the item of an object between the start and stop parameters. Here step and start are optional parameters. If start is not mentioned, then the function starts from the 1st item. The step parameter is used to indicate increment, the default value is set to none.

string1 = 'Ask Python'
slice_object1 = slice(6) 
print(string1[slice_object1])  

nums1 = [1,2,3,4,5,6,7,8,9,10,11]
slice_object2 = slice(1, 6, 2)
print(nums1[slice_object2])   #increament by 2

Output:

Ask Py
[2, 4, 6]

sorted()

sorted(iterable, key=key, reverse=reverse)

This function returns a new sorted list from the items in iterable. The key is an optional parameter used to specify the order of the list to be returned. The reverse is also an optional parameter. It is a boolean that returns true if descending order and false if ascending order.

nums = [50,20,40,10,30]
print(sorted(nums))
print(sorted(nums,reverse = True))    

string1 = 'AskPython'
print(sorted(string1))

Output:

[10, 20, 30, 40, 50]
[50, 40, 30, 20, 10]
[‘A’, ‘P’, ‘h’, ‘k’, ‘n’, ‘o’, ‘s’, ‘t’, ‘y’]

str()

str(object=b'', encoding='utf-8', errors='strict')

This function returns a str a version of an object. The encoding parameter specifies the encoding format, the default value is set to utf-8. The error parameter specifies how to respond in case of failure in decoding. It can be strict, ignore or replace.

s1 = bytes('AskPython', encoding='utf-8',errors='strict')
print(str(s1, encoding='ascii', errors='ignore'))

Output:

AskPython

sum()

sum(iterable, start=0)

The function returns the total of all items of items plus the start parameter. The start parameter is optional and considered 0 by default. The items of iterable should be numbers only.

nums = [10,20,30,40,50]

print(sum(nums))
print(sum(nums,3))

Output:

150
153

super()

super(object)

This function returns the parent class or sibling class of the object. This is useful for accessing inherited methods that have been overridden in a class.

class Employee(object):
  def __init__(self, emp):
    print(emp, 'works for AskPython')
    
class emp(Employee):
  def __init__(self):
    super().__init__('Alex')
    
emp1 = emp()

Output:

Alex works for AskPython

tuple()

tuple(iterable)

This function constructs a tuple for the specified iterable parameter. If no parameters are specified, then the function will construct an empty tuple.

print(tuple())   #empty tuple will be constructed
print(tuple([10,20,30,40]))
print(tuple(('Ask Python')))

Output:

()
(10, 20, 30, 40)
(‘A’, ‘s’, ‘k’, ‘ ‘, ‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)

type()

type(object)
type(name, bases, dict)

This function works in two different ways.

  • If the parameter object is passed, then it will return the type of the object.
  • If three parameters are passed, then it returns a new type of object. The name string is the class name. The bases tuple contains the base classes. if empty, an object, the ultimate base of all classes, is added. The dict dictionary contains attribute and method definitions for the class body.
nums= {10,20,30,40}
print(type(nums))

class Employee:
    name: 'Atlas'
emp = Employee()
print(type(emp))

sample1 = type('AskPython',(Employee,) ,dict(x1='a', x2='b'))
print(type(sample1))

Output:

<class ‘set’>
<class ‘main.Employee’>
<class ‘type>

vars()

vars(object)

This function returns the dictionary mapping attribute (__dict__) for the specified object parameters. In case of no parameters are mentioned, then the function returns methods in the local scope.

print (vars())
print(vars(tuple))

Output:

{‘name’: ‘main’, ‘doc’: None, ‘package’: None, ‘loader’: , ‘spec’: None, ‘annotations’: {}, ‘builtins’: }
{‘repr’: , ‘hash’: , ‘getattribute’: , ‘lt’: , ‘le’: , ‘eq’: , ‘ne’: , ‘gt’: , ‘ge’: , ‘iter’: , ‘len’: , ‘getitem’: , ‘add’: , ‘mul’: , ‘rmul’: , ‘contains’: , ‘new’: , ‘getnewargs’: , ‘index’: , ‘count’: , ‘doc’: “Built-in immutable sequence.\n\nIf no argument is given, the constructor returns an empty tuple.\nIf iterable is specified the tuple is initialized from iterable’s items.\n\nIf the argument is a tuple, the return value is the same object.”}

zip()

zip(*iterables)

This function iterator of tuples based on the iterable passed as a parameter.

  • If no parameter is specified, the function returns an empty iterator.
  • If a single iterable parameter is specified, the function returns an iterator of tuples with each tuple having only one element.
  • If multiple iterables parameters are specified, the function returns an iterator of tuples with each tuple having elements from all the iterables.
nums = [1, 2, 3, 4]
string1 = ['North', 'East', 'West','South']

# Two iterables are passed
x = zip(nums, string1)
list1 = list(x)
print(list1)

Output:

[(1, ‘North’), (2, ‘East’), (3, ‘West’), (4, ‘South’)]

__import__()

__import__(name, globals=None, locals=None, fromlist=(), level=0)

This function is used to change the semantics of the import statement as the statement calls this function. Instead, it is better to use import hooks. This function is rarely used and we do not encourage to use this function.

Conclusion

Python is one of the best-interpreted languages. Built-in functions make it even easier to use this efficiently. In this article, we have covered all the built-in functions available in python, their use along with examples.

For more references click Here.