Newby Coder header banner

Python Built-in Functions

What is a function in Python?

A function is a block of organized, reusable code/statements that is used to perform a specific, related task

More about Functions

Basically, functions can be divided into the following two types:

  1. Built-in functions - Functions that are built into Python
  2. User-defined functions - Functions defined by the users themselves

Python Built-in Functions

Python interpreter has a number of functions available for use, which comes with Python

These functions are called built-in functions

For example, print() function prints the given object to the standard output device (screen) or to the text stream file

Following are built-in functions of Python 3.6

Method Description Example

abs()

returns absolute value of a number - the (positive) distance between a number and zero
>>> abs(-115)
115
>>> abs(100e+13)
1000000000000000.0
>>> abs(-123456789.123456789012345679)
123456789.12345679

all()

returns true when all elements in iterable is true
>>> all([True])
True
>>> all((True, 1, 2, -1534))
True
>>> all((True, 1, 2, 0))
False
>>> all((True, 1, False))
False

any()

Checks if any Element of an Iterable is True
>>> any((True, 1, 2, -1534))
True
>>> any((True, 1, 2, 0))
True
>>> any(("fsdfd", False, 0))
True

ascii()

Returns String Containing Printable Representation
>>> ascii('Œ')
"'\\u0152'"
>>> ascii('©')
"'\\xa9'"
>>> ascii(False)
'False'

bin()

converts integer to binary string
>>> bin(0)
'0b0'
>>> bin(156)
'0b10011100'
>>> bin(-156)
'-0b10011100'

bool()

Converts a Value to Boolean
>>> bool(-10)
True
>>> bool(0)
False
>>> bool(0.1)
True
>>> bool("abc")
True
>>> bool("©")
True
>>> bool(False)
False

bytearray()

returns array of given byte size
>>> bytearray(0)
bytearray(b'')
>>> bytearray(1)
bytearray(b'\x00')
>>> bytearray(10)
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')

bytes()

returns immutable bytes object
>>> bytes(3)
b'\x00\x00\x00'
>>> bytes([0,0,0])
b'\x00\x00\x00'
>>> bytes([3,2,1])
b'\x03\x02\x01'

callable()

Checks if the Object is Callable
>>> callable('abc')
False
>>> callable(10)
False
>>> callable(print)
True
>>> callable(lambda x: x + 1)
True
>>> callable([])
False
>>> callable(list)
True
>>> def func():
...     return 0
...
>>> callable(func)
>>> lmd = lambda x:x+1
>>> callable(lmd)
True

chr()

Returns a Character (a string) from an Integer
>>> chr(52)
'4'
>>> chr(65)
'A'
>>> chr(104)
'h'
>>> chr(91)
'['

classmethod()

returns class method for given function Stack Overflow

compile()

Returns a Python code object
>>> co = compile('print("printed from compile()")', 'test', 'exec')
>>> exec(co)
printed from compile()
>>> eval(co)
printed from compile()

complex()

Creates a Complex Number
>>> complex(1)
(1+0j)
>>> complex(0)
0j
>>> complex((200-2j)/2)
(100-1j)

delattr()

Deletes Attribute From a class object
>>> class Person:
...     name = "Ferb"
...     age=16
...
>>> delattr(Person, 'name')

dict()

Creates a Dictionary
>>> x = dict()
>>> x['age']=16
>>> x['name']='Ferb'
>>> x
{'age': 16, 'name': 'Ferb'}

dir()

Tries to Return Attributes of Object
>>> dir(x)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

divmod()

Returns a Tuple of Quotient and Remainder
>>> divmod(10,2)
(5, 0)
>>> divmod(2,10)
(0, 2)
>>> divmod(-1347.431,131)
(-11.0, 93.56899999999996)

enumerate()

Returns an Enumerate Object
>>> for x in enumerate(range(0,100,12)):
...     print(x)
...
(0, 0)
(1, 12)
(2, 24)
(3, 36)
(4, 48)
(5, 60)
(6, 72)
(7, 84)
(8, 96)

eval()

Runs Python Code Within Program
>>> eval('print("print from eval()")')
print from eval()
>>> square = eval('lambda x: x*x')
>>> square(10)
100

exec()

Executes Dynamically Created Program
>>> exec('print("print from exec()")')
print from exec()
>>> def square(x):
...     return x*x
...
>>> exec('print(square(10))')
100
>>> exec('def add(a,b):\n    return a + b')
>>> add(1,4)
5

filter()

constructs iterator from elements which are true
>>> def is_integer(x):
...     return x == int(x)
...
>>> fltr = filter(integer, [0.1, 0, -15.0, 14.4, 10e+55])
>>> list(fltr)
[0, -15.0, 1e+56]

float()

returns floating point number from number, string
>>> float(100)
100.0
>>> float(1/3)
0.3333333333333333

format()

returns formatted representation of a value
>>> 'String format with arguments {} and {}'.format(15, 12)
'String format with arguments 15 and 12'

frozenset()

returns immutable frozenset object
>>> fs = frozenset([1,2,3])
>>> fs
frozenset({1, 2, 3})
>>> list(fs)
[1, 2, 3]

getattr()

returns value of named attribute of an object
>>> class Person:
...     name="Ferb"
...     age=16
...
>>> p1=Person()
>>> getattr(p1,'name')
'Ferb'
>>> getattr(Person,'age')
16

globals()

returns dictionary of current global symbol table

hasattr()

returns whether object has named attribute
>>> class Person:
...     name="Ferb"
...     age=16
...
>>> p1=Person()
>>> hasattr(p1,'name')
True
>>> hasattr(Person,'age')
True
>>> hasattr(Person,'address')
False

hash()

returns hash value of an object

help()

Invokes the built-in Help System
>>>help(eval)
Help on built-in function eval in module builtins:

eval(source, globals=None, locals=None, /)
    Evaluate the given source in the context of globals and locals.

    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

hex()

Converts to Integer to Hexadecimal

id()

Returns Identify of an Object
>>> class Person:
...     name="Ferb"
...     age=16
...
>>> p1=Person()
>>> id(p1)
139689275476680
>>> id(Person)
19674104
>>> id(dict)
10302432
>>> id(print)
139689374551856

input()

takes input from user and returns a line of string
>>> x=input("Enter x :")
Enter x :15
>>> x
'15'

int()

returns integer from a number or string
>>> int(10.11)
10
>>> int('145')
145
>>> int(False)
0

isinstance()

Checks if a Object is an Instance of Class
>>> class Person:
...     name="Ferb"
...     age=16
...
>>> p1=Person()
>>> isinstance(p1, Person)
True
>>> isinstance('abc', str)
True
>>> isinstance(False, bool)
True

issubclass()

Checks if a Object is Subclass of a Class

iter()

returns iterator for an object

len()

Returns Length of an Object

list() Function

creates list in Python

locals()

Returns dictionary of a current local symbol table

map()

Applies Function and Returns a List

max()

returns largest element

memoryview()

returns memory view of an argument

min()

returns smallest element

next()

Retrieves Next Element from Iterator

object()

Creates a Featureless Object

oct()

converts integer to octal

open()

Returns a File object

ord()

returns Unicode code point for Unicode character

pow()

returns x to the power of y

print()

Prints the Given Object

property()

returns a property attribute

range()

return sequence of integers between start and stop

repr()

returns printable representation of an object

reversed()

returns reversed iterator of a sequence

round()

rounds a floating point number to ndigits places

set()

returns a Python set

setattr()

sets value of an attribute of object

slice()

creates a slice object specified by range()

sorted()

returns sorted list from a given iterable

staticmethod()

creates static method from a function

str()

returns informal representation of an object

sum()

Add items of an Iterable

super()

Allow you to Refer Parent Class by super

tuple() Function

Creates a Tuple

type()

Returns Type of an Object

vars()

Returns __dict__ attribute of a class

zip()

Returns an Iterator of Tuples

__import__()

Advanced Function Called by import