Python language is one of the fastest growing programming language used in many fields like :- artificial intelligence, machine learning, web development, gaming so on. It is widely used language because of the availability great community support, built-in functions, built-in modules, and many various libraries for different purposes.
In this article we are only going to talk about almost all the built-in functions of python along with their python syntax and examples in an easy and reliable manner.
Iterable =>python iterable object like :- list, tuple, & dictionary.
Any() parameters
Iterable => iterable object like :- list, tuple, & dictionary.
This function escape the non-Ascii characters with ASCII characters using /x, /u, or /U.
Ascii() Examples
Bin() parameters
x => an integer number.
Bool() parameters
Object => python object like string, number, etc.
Bool() Examples
Bytearray() parameters
Source - source to use when creating array of byte object. If it is an integer, bytearray object is created of that size. If it is a string, another parameter i.e encoding is required.
Encoding - form of encoding of a string like 'utf-8', 'ascii' .
Errors - specific what to do when error occurs.
The difference between Bytearray and Bytes is that bytes object are immutable while bytearray object are mutable.
Bytes() parameters
Source - source to use when creating array of bytes. If it is an integer, bytearray object is created of that size. If it is a string, another parameter i.e encoding is required.
Encoding - form of encoding of a string.
Errors (optional) - specify what to do when error occurs.
Callable() parameters
Object - any python object you want to check if it is callable or not. Callable objects like classes, function, etc.
Integer ranges from => 0 - 1,114,111
Chr() parameters
integer - an integer number.
Int() Examples
@classmethod Examples
compile() parameters
source - source can be normal string, byte string, or AST object
filename - file name from which source comes. If no source comes from file you can write ("") like this.
mode - mode can be 'exec', 'eval', or 'single'. exec, if source consist of blocks of statement, eval, if source consist of single expression and single, if source is a single interactive statement
flags (flags) - control which future statements effect the compilation of source (default : 0).
dont_inherit (optional) - it also control which future statements effect the complication of source (default : False).
optimize (optional) => optimization level of the compiler (default = -1).
Compile() Examples
complex() parameters
Complex() Examples
delattr() parameters
object - name of the python object.
attribute - name of the attribute you want to delete.
Delattr() Examples
dict() parameters
**kwargs - keyword arguments like (key=value, ..)
Dict() Examples
dir() parameters
object - object you want to see the attributes and methods of.
Dir() Examples
divmod() Parameters
dividend - number you want to divide.
divisor - number you want to divide from.
Divmod() Examples
enumerate parameters
iterable - python iterable object.
start (optional) - start number of the enumerate object. Default=0.
Enumerate() Examples
eval() parameters
expression - string evaluated as a python expression.
globals (optional) - dictionary containing global parameters.
locals (optional) - dictionary containing local parameters.
Eval() Examples
Object - object can be string or a code object.
Globals (optional) - dictionary containing global parameters.
locals (optional) - dictionary containing local parameters.
from math import *
Filter() parameters
Function - function name from which you want to filter.
Iterable - iterable you want to filter.
Filter() Examples
Float() parameters
Value - any number.
Float() Examples
Format() parameters
Value - any value
Format - format in which you want to covert.
Format() Examples
Frozenset() parameters
Iterable -like list, tuple, dictionary, set.
Getattr() parameters
Object - any object.
Attribute - name of the attribute you want value of.
Default (optional) - returning value if no attribute found.
Getattr() Examples
Globals() Examples
Hasattr() parameters
Object - any python object.
Name - name of the attribute.
Hasattr() Examples
hash() parameters
object - any python object.
Hash() Examples
Help() parameters
Object - any python object.
Help() Examples
hex() parameters
Value - an integer number.
id() parameters
object - any python object.
Id() Examples
Input() parameters
promt - written string before input.
Input() Examples
int() parameters
value - any number or string that can be converting into integer.
base (optional) - number specifying format of number (default : 10).
Int() Examples
isinstance() parameters
object - name of a python object you want to check.
class - class name in which you want to check the availability of object.
Isinstance() Examples
Issubclass() parameters
subclass - class name.
class - class name.
Issubclass() Examples
Iter() Examples
len() parameters
object - any python object.
Len() Examples
4
iterable - an iterator object
List() Examples
Max() Examples
Memoryview() parameters
Memoryview() Examples
Min() Examples
next() parameters
iterator - an iterable object.
default (default) - default value return if iterable reaches the end.
Next() Examples
Object() Examples
oct() parameters
value - an integer number.
Open() Parameters
File => name of the file.
Buffering (optional) => integer to set buffering policy.
Open() Examples
ord() parameters
character - any character.
Ord() Examples
pow() parameters
base - base number.
exponent - exponent number.
modulas (optional) - modulas number.
Print() parameters
Object - any object.
Sep (optional) => specify how to separate object, if more then one.
End (optional) => specify what to do at the end (default : '/n').
File (optional) => an object with write(string) method.
Flush (optional) => a Boolean value, specify if the output is buffered (False) or flushed (True). Default is False.
@property Examples
Range() Parameters
Start - integer number specifying starting position of the range.
Stop - integer number specifying end position of the range.
Step (optional) - number by which number increment. Default: 1 .
Range() Examples
Repr() parameters
Object - an object.
Repr() Examples
Reversed() parameters
Sequence - an iterable object.
Round() parameters
Value - any number you want to round off.
Digits (optional) - number of decimals required.
Round() Examples
Set() parameters
Iterable - an iterable object.
Set() Examples
Setattr() parameters
Object - an object.
Name - attribute name you want to set.
Value - value you want to set.
Slice() parameters
Start - an integer number specifying position from which slicing starts.
Stop - an integer specifying position at which slicing stops.
Step (optional) - an integer number specifying steps to take while slicing.
Slice() Examples
Sorted() parameters
Iterable - an iterable object like list, tuple.
Key (optional) - function to use when sorting. Default: none.
Reverse (optional) - a Boolean value (default = False) . If True reverse the order.
Staticmethod() Examples
Str() parameters
Object - any object to convert into a string.
Encoding (optional) - format of encoding (default = UTF-8).
Error (optional) - specifying what if error occurs in decoding.
Str() Examples
a = str(37)
print(a)
Sum() parameters
Iterable - an iterable object.
Start (optional) - number added to the sum.
Super() Examples
Tuple() parameters
Iterable - an iterable object.
Tuple() Examples
Type() parameters
Object - any python
object.
Bases (optional) - specify the base class.
Dict (optional) - namespace specifying definition for class.
Type() Examples
Var() parameters
Object => any object with "__dict__" attribute.
Var() Examples
Zip() Examples
Python built-in functions
Python built-in functions are the functions which are pre-defined i.e functions which are already available in the python for use.1. Abs()
Abs() or absolute function is used to return absolute value of a number i.e if the number is negative in makes it positive.
Syntax
abs(num) ,
where num = any number.
Abs() parameters
Num => can be integer, float, or complex number. If complex number only magnitude is returned.
Abs() Examples
# integer number
num1 = abs(-3.5)
print(num1)
num2 = abs(4.6)
print(num2)
#float number
num3 = abs(-35.332)
print(num3)
#complex number
num4 = abs(-4 + 6j)
print(num4)
Output
3.5
4.6
35.332
7.211102550927978
2. All()
All() python function returns Boolean value; returns true if all values of iterable are "true" and "false" if not.
Syntax
all(iterable)
All() parametersIterable =>python iterable object like :- list, tuple, & dictionary.
All() Examples
list = ['one', 'two', 'three']
a = all(list)
print(a)
tuple = (1,0,2,3)
b = all(tuple)
print(b)
dic = {}
c = all(dic)
print(c)
False
True
a = all(list)
print(a)
tuple = (1,0,2,3)
b = all(tuple)
print(b)
dic = {}
c = all(dic)
print(c)
Output
TrueFalse
True
3. Any()
Any() function also returns Boolean value i.e return "True" if any value of iterable is true and return "false" if not.
Syntax
any(iterable)
Any() parameters
Iterable => iterable object like :- list, tuple, & dictionary.
Any() Examples
list = ['one', 'two', 'three']
a = any(list)
print(a)
tuple = (0,0,0,0)
b = any(tuple)
print(b)
dic = {}
c = any(dic)
print(c)
False
False
a = any(list)
print(a)
tuple = (0,0,0,0)
b = any(tuple)
print(b)
dic = {}
c = any(dic)
print(c)
Output
TrueFalse
False
4. ASCII(object)
ascii() function returns a python string containing printable representation of python object.This function escape the non-Ascii characters with ASCII characters using /x, /u, or /U.
Syntax
ascii(object)
Ascii() parameters
Object => python objects like :- string, list, tuple, dictionary, etc.Ascii() Examples
list = ['one', 'two', 'three', 'çà t']
a = ascii(list)
print(a)
string = 'helló world'
b = ascii(string)
print(b)
'hell\xf3 world'
a = ascii(list)
print(a)
string = 'helló world'
b = ascii(string)
print(b)
Output
['one', 'two', 'three', '\xe7\xe0t']'hell\xf3 world'
5. Bin()
Bin() python function returns binary string of a integer number and always starts with prefix "0b".
Syntax
bin(x)
Bin() parameters
x => an integer number.
Bin() Examples
a = 10
b = bin(a)
print(b)
c = 284
d = bin(c)
print(d)
0b100011100
b = bin(a)
print(b)
c = 284
d = bin(c)
print(d)
Output
0b10100b100011100
6. Bool()
Bool() function always return value in "true" or "false". Returns False if object is null, false, or 0 ; Otherwise returns True.
Syntax
bool(object)
Bool() parameters
Object => python object like string, number, etc.
Bool() Examples
a = []
print(bool(a))
b = ['python', 'language']
c = bool(b)
print(c)
string =''
a = bool(string)
print(a)
True
False
print(bool(a))
b = ['python', 'language']
c = bool(b)
print(c)
string =''
a = bool(string)
print(a)
Output
FalseTrue
False
7. Bytearray()
Bytearray() function returns a python mutable array of a byte.
Syntax
Bytearray(source, encoding, errors)
Bytearray() parameters
Source - source to use when creating array of byte object. If it is an integer, bytearray object is created of that size. If it is a string, another parameter i.e encoding is required.
Encoding - form of encoding of a string like 'utf-8', 'ascii' .
Errors - specific what to do when error occurs.
Bytearray() Examples
a = [2,35, 55, 44 ,46, 44]
b = bytearray(a)
b.append(4)
print(b)
a = bytearray(3)
print(a)
a = bytearray('python', 'utf-8')
print(a)
bytearray(b'\x00\x00\x00')
bytearray(b'python')
b = bytearray(a)
b.append(4)
print(b)
a = bytearray(3)
print(a)
a = bytearray('python', 'utf-8')
print(a)
Output
bytearray(b'\x02#7,.,\x04')bytearray(b'\x00\x00\x00')
bytearray(b'python')
8. Bytes()
This function returns the python byte object. It is a immutable array of a byte range from 0 <=x <256.The difference between Bytearray and Bytes is that bytes object are immutable while bytearray object are mutable.
Syntax
bytes(source, encoding, errors)
Bytes() parameters
Source - source to use when creating array of bytes. If it is an integer, bytearray object is created of that size. If it is a string, another parameter i.e encoding is required.
Encoding - form of encoding of a string.
Errors (optional) - specify what to do when error occurs.
Bytes() Examples
a = [2,35, 55, 44 ,46, 44]
b = bytes(a)
print(b)
a = bytes(3)
print(a)
a = bytes('python', 'utf-8')
print(a)
b'\x00\x00\x00'
b'python'
b = bytes(a)
print(b)
a = bytes(3)
print(a)
a = bytes('python', 'utf-8')
print(a)
Output
b'\x02#7,.,'b'\x00\x00\x00'
b'python'
9. Callable()
Callable() function returns Boolean value. It returns True if object is callable and False if not.
Syntax
callable(object)
Callable() parameters
Object - any python object you want to check if it is callable or not. Callable objects like classes, function, etc.
Callable() Examples
def func() :
print('hello world')
f = callable(func)
print(f)
a = 4848
b = callable(a)
print(b)
False
print('hello world')
f = callable(func)
print(f)
a = 4848
b = callable(a)
print(b)
Output
TrueFalse
10. Chr()
Chr() function returns a character for an integer represents unicode code point of a character.Integer ranges from => 0 - 1,114,111
Syntax
chr(integer)
Chr() parameters
integer - an integer number.
Int() Examples
a = chr(58), chr(38)
print(a)
print(a)
Output
(':', '&')11. @Classmethod
Classmethod function of python returns a class method for a given method.
Syntax
@classmethod
@classmethod
@classmethod Examples
class employer:
bonus = 5000
@classmethod
def set_bonus(cls, amount):
cls.bonus = amount
puneet = employer()
print('bonus : ',puneet.bonus)
employer.set_bonus(6000)
print('new bonus : ',puneet.bonus)
new bonus : 6000
bonus = 5000
@classmethod
def set_bonus(cls, amount):
cls.bonus = amount
puneet = employer()
print('bonus : ',puneet.bonus)
employer.set_bonus(6000)
print('new bonus : ',puneet.bonus)
Output
bonus : 5000new bonus : 6000
12. Compile()
The compile() function is not used commonly.
Syntax
compile(source, filename, mode, flags, dont_inherit, optimize)
compile() parameters
source - source can be normal string, byte string, or AST object
filename - file name from which source comes. If no source comes from file you can write ("") like this.
mode - mode can be 'exec', 'eval', or 'single'. exec, if source consist of blocks of statement, eval, if source consist of single expression and single, if source is a single interactive statement
flags (flags) - control which future statements effect the compilation of source (default : 0).
dont_inherit (optional) - it also control which future statements effect the complication of source (default : False).
optimize (optional) => optimization level of the compiler (default = -1).
Compile() Examples
a = 5
b = compile('a+5', '' ,'eval')
c = eval(b)
print(c)
Output => 10
x = 4
bytes_str = bytes('x==4', 'utf-8')
code = compile(bytes_str, '', 'eval')
result = eval(code)
print(result)
Output => True
import ast
a = ast.parse("print('hello world')")
b = compile(a, '', 'exec')
c = exec(b)
Output => hello world
a = 5
b = 40
c = compile('a*b, "/n",print("a*b =",a*b)', '', 'exec')
d = exec(c)
Output => a*b = 200
a = compile('37', 'j', 'single')
exec(a)
Output => 3713. Complex()
Complex() function takes 2 arguments - real number and imaginary number and returns complex number.
Syntax
complex(real, imaginary)
complex() parameters
real - real number of the complex number.
imaginary - imaginary number of the complex number.
Complex() Examples
a = complex(4,8)
print(a)
print(a)
Output
(4+8j)14. Delattr()
Delattr() function takes 2 arguments - class & attribute. And delete specific attribute of a class.
Syntax
delattr(object, attribute)
delattr() parameters
object - name of the python object.
attribute - name of the attribute you want to delete.
Delattr() Examples
class python:
a = 68
print(python.a)
c = delattr(python,'a')
print(c)
None
a = 68
print(python.a)
c = delattr(python,'a')
print(c)
Output
68None
15. Dict()
Dict() function creates a new python dictionary object.
Syntax
dict(**kwargs)
dict() parameters
**kwargs - keyword arguments like (key=value, ..)
Dict() Examples
dictionary = dict(((1,'one'),(2,'two'),(3,'three'),(4,'four')))
print(dictionary)
print(dictionary)
Output
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}16. Dir()
Dir() function returns a python list of specified object's attributes and methods.
Syntax
dir(object)
dir() parameters
object - object you want to see the attributes and methods of.
Dir() Examples
a = 'my name is python'
b = dir(a)
print(b)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
b = dir(a)
print(b)
Output
17. Divmod()
Divmod() function takes 2 arguments - dividend & divisor ; and returns tuple of quotient and reminder.
Syntax
divmod(dividend, divisor)
divmod() Parameters
dividend - number you want to divide.
divisor - number you want to divide from.
Divmod() Examples
a = divmod(22,8)
print(a)
print(a)
output
(2, 6)18.Enumerate()
Enumerate() function refers to the python built-in function which is used to add counter to the iterable and return it as an enumerate object.
Syntax
enumerate(iterable,start)
enumerate parameters
iterable - python iterable object.
start (optional) - start number of the enumerate object. Default=0.
Enumerate() Examples
array = [3,83,47,38,20]
a = enumerate(array)
for i in a:
print(i)
(1, 83)
(2, 47)
(3, 38)
(4, 20)
a = enumerate(array)
for i in a:
print(i)
Output
(0, 3)(1, 83)
(2, 47)
(3, 38)
(4, 20)
19. Eval()
Eval() function takes a string as an argument and evaluate it as an python expression.
Syntax
eval(expression, globals, locals)
eval() parameters
expression - string evaluated as a python expression.
globals (optional) - dictionary containing global parameters.
locals (optional) - dictionary containing local parameters.
Eval() Examples
x=3
a = eval('x+38')
print(a)
b = eval('x+y',{'x':36,'y':44})
print(b)
80
a = eval('x+38')
print(a)
b = eval('x+y',{'x':36,'y':44})
print(b)
Output
4180
20. Exec()
Exec() function execute the python code.
Syntax
exec(object, globals, locals)
exec() parameters
Object - object can be string or a code object.
Globals (optional) - dictionary containing global parameters.
locals (optional) - dictionary containing local parameters.
Exec() Examples
from math import *
exec("print(len('jay'))")
exec('print(fact(10))', {'fact': factorial})
Output
3
3628800
21. Filter()
Filter() function returns an iterator for each element of specified iterable for which python function returns true.
Syntax
filter(function, iterable)
Function - function name from which you want to filter.
Iterable - iterable you want to filter.
Filter() Examples
def func(x):
if x>10:
return True
else:
return False
list = [3,48,3,0,7,28,4,5]
a = filter(func,list)
for i in a:
print(i)
28
if x>10:
return True
else:
return False
list = [3,48,3,0,7,28,4,5]
a = filter(func,list)
for i in a:
print(i)
Output
4828
22. Float()
This built-in function returns float value of specified value.
Syntax
float(value)
Value - any number.
Float() Examples
a = float(38)
print(a)
38.0
print(a)
Output
38.0
23. Format()
Convert a specified value into specified format.
Syntax
format(value, format)
Value - any value
Format - format in which you want to covert.
Format() Examples
a = 5
print('a={}'.format(a))
print('a={}'.format(a))
Output
a=524. Frozenset()
Frozenset() function returns the immutable or unchangeable frozenset object.
Syntax
frozenset(iterable)
Iterable -like list, tuple, dictionary, set.
Frozenset() Examples
list = [3,73,37,4,6,8]
a = frozenset(list)
print(a)
a = 'python'
print(frozenset(a))
frozenset({3, 4, 37, 6, 8, 73})
frozenset({'n', 'o', 'h', 't', 'p', 'y'})
a = frozenset(list)
print(a)
a = 'python'
print(frozenset(a))
Output
frozenset({'n', 'o', 'h', 't', 'p', 'y'})
25. Getattr()
Getattr() function returns the value of the specific object's attribute.
Syntax
getattr(object, attribute, default)
Getattr() parameters
Object - any object.
Attribute - name of the attribute you want value of.
Default (optional) - returning value if no attribute found.
Getattr() Examples
class fruits:
f1 = 'mango'
f2 = 'banana'
f3 = 'apple'
a = getattr(fruits, 'f3')
b = getattr(fruits,'f3','orange')
c = getattr(fruits,'f5','orange')
print(a)
print(b)
print(c)
apple
apple
orange
f1 = 'mango'
f2 = 'banana'
f3 = 'apple'
a = getattr(fruits, 'f3')
b = getattr(fruits,'f3','orange')
c = getattr(fruits,'f5','orange')
print(a)
print(b)
print(c)
Output
apple
orange
26. Globals()
Globals() function is the python built-in function that returns the dictionary representing current global symbol table.
Syntax
globals()
Globals() Examples
print(globals())
{'__name__': '__main__', '__file__': '/data/user/0/ru.iiec.pydroid3/files/temp_iiec_codefile.py', '__builtins__': <module 'builtins' (built-in)>, '__warningregistry__': {'version': 0}}
Output
27. Hasattr()
Hasattr(), returns True if object as a specific attribute ; else False.
Syntax
hasattr(object, name)
Hasattr() parameters
Object - any python object.
Name - name of the attribute.
Hasattr() Examples
class fruits:
f1 = 'mango'
f2 = 'banana'
f3 = 'apple'
a = hasattr(fruits, 'f3')
print(a)
f1 = 'mango'
f2 = 'banana'
f3 = 'apple'
a = hasattr(fruits, 'f3')
print(a)
Output
True28. Hash()
This python built-in function returns hash value of the specified object.
Syntax
hash(object)
object - any python object.
Hash() Examples
a = 'jay khandelwal'
b = hash(a)
print(b)
-4414160042294183326
b = hash(a)
print(b)
Output
29. Help()
Help() function of python helps to get the documentation of the specified class, function, variable, etc.
Syntax
help(object)
Object - any python object.
Help() Examples
help(int)
class int(object)
| int([x]) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating point
| numbers, this truncates towards zero.
|
| If x is not a number or if base is given, then x must be a string,
| bytes, or bytearray instance representing an integer literal in the
| given base. The literal can be preceded by '+' or '-' and be surrounded
| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
| Base 0 means to interpret the base from the string as an integer literal.
| >>> int('0b100', base=0)
| 4
--More--
Output
Help on class int in module builtins:class int(object)
| int([x]) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating point
| numbers, this truncates towards zero.
|
| If x is not a number or if base is given, then x must be a string,
| bytes, or bytearray instance representing an integer literal in the
| given base. The literal can be preceded by '+' or '-' and be surrounded
| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
| Base 0 means to interpret the base from the string as an integer literal.
| >>> int('0b100', base=0)
| 4
--More--
30. Hex()
Hex() function returns lowercase hexadecimal string of the specified integers number.
Syntax
hex(value)
Value - an integer number.
Hex() Examples
a = hex(37)
print(a)
0x25
print(a)
Output
31. Id()
Id() function returns identity of the object in integer form.
Syntax
id(object)
object - any python object.
Id() Examples
a = 'hello world'
b = id(a)
print(b)
548099915440
b = id(a)
print(b)
Output
32. Input()
Input() is a python built in function allow the user to input. It converts the input value to the string.
Syntax
input(promt)
promt - written string before input.
Input() Examples
a = input('enter your name :-')
print('welcome,',a)
enter your name :-jay
welcome, jay
print('welcome,',a)
Output
welcome, jay
33. Int()
This python built-in function returns the integer number from the specified number or string (string must be number not alphabet).
Syntax
int(value, base)
value - any number or string that can be converting into integer.
base (optional) - number specifying format of number (default : 10).
Int() Examples
a = int('20')
print(a)
b = int('20',30)
print(b)
20
60
print(a)
b = int('20',30)
print(b)
Output
20
60
34. Isinstance()
Isinstance() function returns Boolean value ; True if specified object is an instance of specified class and return Fasle if not.
Syntax
ininstance(object, class)
object - name of a python object you want to check.
class - class name in which you want to check the availability of object.
Isinstance() Examples
a = '48'
b = isinstance(a,int)
print(b)
d = isinstance(38,(str,list,tuple,int))
print(d)
class car:
name1 = 'bmw'
name2 ='honda'
car1 = car()
z = isinstance(car1,car)
print(z)
True
True
b = isinstance(a,int)
print(b)
d = isinstance(38,(str,list,tuple,int))
print(d)
class car:
name1 = 'bmw'
name2 ='honda'
car1 = car()
z = isinstance(car1,car)
print(z)
Output
FalseTrue
True
35. Issubclass()
This function also returns boolean value ; True if specified class is the subclass of another specified class and return False if not.
Syntax
insubclass(subclass, class)
subclass - class name.
class - class name.
Issubclass() Examples
Class fruits:
a = 'fruits'
class apple(fruits):
name = 'apple'
a = issubclass(apple,fruits)
print(a)
a = 'fruits'
class apple(fruits):
name = 'apple'
a = issubclass(apple,fruits)
print(a)
Output
True36. Iter()
Iter() function return an iterator object.
Syntax
iter(object, sentinel)
Iter() Parameters
Object => an iterable object.
Sentinel (optional) => when sentinel value is given, the object must be a callable object. If the value returned is equal to sentinel value iteration will stop.
a = iter(['apple','mango','guava'])
for i in a:
print(i)
mango
guava
for i in a:
print(i)
Output
applemango
guava
37. Len()
This is commonly used python built-in function. This function calculates the length of the specified argument. An argument may be string, range, list, tuple, bytes, dictionary, set, or frozenset.
Syntax
len(object)
object - any python object.
Len() Examples
list = ['delhi', 'up', 'punjab','maharastra']
a = len(list)
print(a)
Output
38. List()
List() function creates a python list object.
Syntax
list(iterable)
list() parametersiterable - an iterator object
List() Examples
a = list((1,27,7,8,0,4))
print(a)
[1, 27, 7, 8, 0, 4]
print(a)
Output
[1, 27, 7, 8, 0, 4]
39. Locals()
Local() python function returns a python dictionary of the local symbol table. The content of this dictionary should not be modified.
Syntax
locals()
Locals() Examples
a = locals()
print(a)
{'__name__': '__main__', '__file__': '/data/user/0/ru.iiec.pydroid3/files/temp_iiec_codefile.py', '__builtins__': <module 'builtins' (built-in)>, '__warningregistry__': {'version': 0}, 'a': {...}}
print(a)
Output
{'__name__': '__main__', '__file__': '/data/user/0/ru.iiec.pydroid3/files/temp_iiec_codefile.py', '__builtins__': <module 'builtins' (built-in)>, '__warningregistry__': {'version': 0}, 'a': {...}}
40. Map()
The map() function applies the specified function for each item in specified iterable.
Syntax
map(function, iterable)
Map() Parameters
Function => function you want to execute for each iterable.
Iterable => an iterable object.
Map() Examples
def func(x):
a = len(x)
return a
list = ['one','two', 'three']
b = map(func, list)
print(tuple(b))
a = len(x)
return a
list = ['one','two', 'three']
b = map(func, list)
print(tuple(b))
Output
(3, 3, 5)41. Max()
This function returns the maximum value from the specified iterables.
Syntax
max(iterables)
Max() Parameters
Iterables => an iterable object like list, tuple, set.
list = ['one','two', 'three', 'four']
list2 = [2,27,48,28,4,40]
print(max(list))
print(max(list2))
48
list2 = [2,27,48,28,4,40]
print(max(list))
print(max(list2))
Output
two48
42. Memoryview()
Memoryview() function is a python built in function used to show the memory view of the specified argument.
Syntax
memoryview(object)
object - any python object.
Memoryview() Examples
a = bytes('python','utf-8')
b = memoryview(a)
print(b)
print(b[0])
b = memoryview(a)
print(b)
print(b[0])
Output
<memory at 0x7f92969348>
112 # unicode of the 1st letter "p"
43. Min()
This python function return the minimum value from the specified iterables.
Syntax
min(iterables)
Min() Parameters
Iterables => iterable python object like list, tuple, set.
list = ['one','two', 'three', 'four']
list2 = [2,27,48,28,4,40]
print(min(list))
print(min(list2))
2
list2 = [2,27,48,28,4,40]
print(min(list))
print(min(list2))
Output
four2
44. Next()
This function calls __next__() method to retrieve next item from iterator.
Syntax
next(iterator, default)
iterator - an iterable object.
default (default) - default value return if iterable reaches the end.
Next() Examples
a = [2,35, 55, 44 ,46, 44]
c = iter(a)
b = next(c)
print(b)
2
c = iter(a)
b = next(c)
print(b)
Output
2
45. Object()
Object() function returns the new featureless python object.
Syntax
Object()
Object()
Object() Examples
a = object()
print(a)
print(a)
Output
<object object at 0x7f9f2f70d0>46. Oct()
This python built-in function returns octal string from the specified integer number. Always starts with prefix '0o'.
Syntax
oct(value)
value - an integer number.
Oct() Examples
a = oct(37)
print(a)
0o45
print(a)
Output
0o45
47. Open()
This function opens the specified file and raise OS error, if file not opened.
Syntax
open(file, mode, buffering)
Open() Parameters
File => name of the file.
Mode (optional) => mode in which you want to open the file. Modes :- 'r' : read ; 'w' : write ; 'a' : append ; 'x' : create ; 't' : text ; 'b' : binary ;. Default is 'r' .
Buffering (optional) => integer to set buffering policy.
Open() Examples
f = open("xyz.txt", "r")
print(f.read())
print(f.read())
Output
Hello! welcome to python built-in functions tutorial48. Ord()
Ord() function returns an integer number represent a unicode point of a given unicode character.
Syntax
ord(character)
character - any character.
Ord() Examples
a = ord('&')
print(a)
38
print(a)
Output
38
49. Pow()
Pow() function returns value of 'x' to the power 'y' .
Syntax
pow(base, exponent, modulas)
base - base number.
exponent - exponent number.
modulas (optional) - modulas number.
Pow() Examples
a = pow(9,2)
print(a)
81
print(a)
Output
81
50. Print()
It refers to the commonly used python built-in function. It is used to print the given object to the screen or to the standard output device.
Syntax
print(object, sep, end, flush)
Object - any object.
Sep (optional) => specify how to separate object, if more then one.
End (optional) => specify what to do at the end (default : '/n').
File (optional) => an object with write(string) method.
Flush (optional) => a Boolean value, specify if the output is buffered (False) or flushed (True). Default is False.
Print() Examples
print('hello world')
hello world
Output
hello world
51. @Property
This function returns a property attribute. It allow us to access function like an attribute.
Syntax
@property
@property Examples
class employer:
def __init__(self, f_name, l_name):
self.f_name = f_name
self.l_name = l_name
@property
def full_name(self):
return self.f_name + ' ' +self.l_name
e1 = employer('puneet','sharma')
print(e1.full_name)
def __init__(self, f_name, l_name):
self.f_name = f_name
self.l_name = l_name
@property
def full_name(self):
return self.f_name + ' ' +self.l_name
e1 = employer('puneet','sharma')
print(e1.full_name)
Output
puneet sharma52. Range()
Range() function returns to the immutable sequence between the numbers started from given number to the specified end number.
Syntax
range(start, stop, step)
Start - integer number specifying starting position of the range.
Stop - integer number specifying end position of the range.
Step (optional) - number by which number increment. Default: 1 .
Range() Examples
a = range(3,17)
b = range(3,17,3)
print(list(a))
print(list(b))
[3, 6, 9, 12, 15]
b = range(3,17,3)
print(list(a))
print(list(b))
Output
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16][3, 6, 9, 12, 15]
53. Repr()
This python function returns a printable version of an object.
Syntax
repr(object)
Object - an object.
Repr() Examples
a = 'python'
print(repr(a))
print(repr(a))
Output
'python'54. Reversed()
Reversed() function returns iterator object by reversing it.
Syntax
reversed(sequence)
Sequence - an iterable object.
Reversed() Examples
a =('mango', 'apple', 'banana','orange')
b = reversed(a)
print(tuple(b))
('orange', 'banana', 'apple', 'mango')
b = reversed(a)
print(tuple(b))
Output
('orange', 'banana', 'apple', 'mango')
55. Round()
Round() function returns the round off version of a float number to the given number of decimals.
Syntax
rount(value, digits)
Value - any number you want to round off.
Digits (optional) - number of decimals required.
Round() Examples
a = 30.4848
b = round(a,2)
print(b)
b = round(a,2)
print(b)
Output
30.4856. Set()
This function creates new python set object.
Syntax
set(iterable)
Iterable - an iterable object.
Set() Examples
a = set((47,38,28,59))
print(a)
print(a)
Output
{59, 28, 38, 47}57. Setattr()
This python function is used for as the name suggests, settings the attribute value.
Syntax
setattr(object, name, value)
Object - an object.
Name - attribute name you want to set.
Value - value you want to set.
Setattr() Examples
class fruits:
name1 = 'apple'
name2 = 'orange'
a = fruits()
print(a.name1)
b = setattr(a,a.name1,'mango')
c = getattr(a, a.name1)
print(c)
mango
name1 = 'apple'
name2 = 'orange'
a = fruits()
print(a.name1)
b = setattr(a,a.name1,'mango')
c = getattr(a, a.name1)
print(c)
Output
applemango
58. Slice()
This function returns slice object.
Syntax
slice(start, stop, step)
Start - an integer number specifying position from which slicing starts.
Stop - an integer specifying position at which slicing stops.
Step (optional) - an integer number specifying steps to take while slicing.
Slice() Examples
list = ['apple','orange','mango','banana']
a = slice(2)
print(list[a])
a = slice(2)
print(list[a])
Output
['apple', 'orange']59. Sorted()
Sorted() function returns a sorted list of specified iterable object i.e sort either alphabetical or numerically.
Syntax
sorted(iterable, key, reverse)
Iterable - an iterable object like list, tuple.
Key (optional) - function to use when sorting. Default: none.
Reverse (optional) - a Boolean value (default = False) . If True reverse the order.
Sorted() Examples
list = ['apple','orange','mango','banana']
a = sorted(list)
print(a)
a = sorted(list)
print(a)
Output
['apple', 'banana', 'mango', 'orange']60. Staticmethod
Converts a method into static method.
Syntax
@staticmehod
@staticmehod
Staticmethod() Examples
class employer:
def __init__(self, name):
self.name = name
@staticmethod
def say_hi():
print('hello')
e1 = employer('hritik')
e1.say_hi()
def __init__(self, name):
self.name = name
@staticmethod
def say_hi():
print('hello')
e1 = employer('hritik')
e1.say_hi()
Output
hello61. Str()
Str() function convert the given value into string.
Syntax
Str(object, encoding, error)
Object - any object to convert into a string.
Encoding (optional) - format of encoding (default = UTF-8).
Error (optional) - specifying what if error occurs in decoding.
Str() Examples
a = str(37)
print(a)
Output
3762. Sum()
It returns the sum of all the numbers in an iterable.
Syntax
Sum(iterable, start)
Iterable - an iterable object.
Start (optional) - number added to the sum.
Sum() Examples
list = [3,73,48,25,35,3,9]
list1 = [20,40,30]
a = sum(list)
b = sum(list1,10)
print(a)
print(b)
100
list1 = [20,40,30]
a = sum(list)
b = sum(list1,10)
print(a)
print(b)
Output
196100
63. Super()
Super() function gives access of methods and properties of the parent class to its subclass
Syntax
Super()
Super()
Super() Examples
class fruits:
def __init__(self, text):
self.text = text
def printer(self):
print(self.text)
class apple(fruits):
def __init__(self, text):
super().__init__(text)
apple1 = apple('hello my name is apple')
apple1.printer()
def __init__(self, text):
self.text = text
def printer(self):
print(self.text)
class apple(fruits):
def __init__(self, text):
super().__init__(text)
apple1 = apple('hello my name is apple')
apple1.printer()
Output
hello my name is apple64. Tuple()
The tuple() function creates new python tuple object.
Syntax
tuple(iterable)
Iterable - an iterable object.
Tuple() Examples
list1 = [20,40,30]
a = tuple(list1)
print(a)
a = tuple(list1)
print(a)
Output
(20, 40, 30)
65. Type()
The type() function is used to know the type of object like :- string, list, dictionary, etc.
Syntax
type(object, bases, dict)
Object - any python
object.
Bases (optional) - specify the base class.
Dict (optional) - namespace specifying definition for class.
Type() Examples
list1 = [20,40,30]
string = 'python'
a = type(list1)
b = type(string)
print(a)
print(b)
<class 'str'>
string = 'python'
a = type(list1)
b = type(string)
print(a)
print(b)
Output
<class 'list'><class 'str'>
66. Var()
The var() function returns the __dict__ attribute of the specified object.
Syntax
var(object)
Object => any object with "__dict__" attribute.
Var() Examples
class fruits:
name1 = 'apple'
name2 = 'mango'
a = vars(fruits)
print(a)
{'__module__': '__main__', 'name1': 'apple', 'name2': 'mango', '__dict__': <attribute '__dict__' of 'fruits' objects>, '__weakref__': <attribute '__weakref__' of 'fruits' objects>, '__doc__': None}
name1 = 'apple'
name2 = 'mango'
a = vars(fruits)
print(a)
Output
{'__module__': '__main__', 'name1': 'apple', 'name2': 'mango', '__dict__': <attribute '__dict__' of 'fruits' objects>, '__weakref__': <attribute '__weakref__' of 'fruits' objects>, '__doc__': None}
67. Zip()
This python built-in function returns a tuple of iterator by taking iterables as an arguments.
Syntax
zip(iterables)
Zip() Parameters
Iterable => iterable like list, tuple.
list1 = [1,2,3,4]
list2 = ['apple','mango','orange','banana']
a = zip(list1,list2)
print(list(a))
[(1, 'apple'), (2, 'mango'), (3, 'orange'), (4, 'banana')]
list2 = ['apple','mango','orange','banana']
a = zip(list1,list2)
print(list(a))
Output
[(1, 'apple'), (2, 'mango'), (3, 'orange'), (4, 'banana')]
Conclusion
They may overwhelmed at once but as you practice them regularly you can easily learn all python built in functions.
I hope you like this article, know you know about all the python built-in functions.
0 Comments