Best post on built-in functions in python – 1

Built-in functions in python

We have already discussed about Function in Python i.e. user defined functions. In this we are studying built-in functions in python.
Python consists of various function whose functioning is predefined in python itself.
Such functions are called as built-in functions.
There are 68 built-in functions present in python.

built-in functions (itvoyagers.in)

List of few of built-in functions

List of few of built-in functions and its description are as follows :

abs()

It is one of the python built-in functions which returns absolute value of a number. A negative digit is turned to positive.
Example

>>> a=-9
>>> abs(a)
9
>>> abs(0)
0
>>> abs(9)
9
>>> 
>>> abs(-4.2)
4.2

all()

The all() function takes a container as an argument. This built-in function returns True if all values in a python iterable have a Boolean value of True. An empty value has a Boolean value of False.
Example

>>> all(['','',''])
False
>>> all([' ',' ',' '])
True
>>> all([1,2,6])
True

any()

The any() function takes a container as an argument. This built-in function returns True if any one values in a python iterable have a Boolean value of True. An empty value has a Boolean value of False.
Example

>>> any(['','',''])
False
>>> any([' ',' ',' '])
True
>>> any([1,0,0])
True
>>> any([0,0,0])
False

bin()

The bin() built-in functions returns the binary representation of an integer.
Example

>>> bin(10)
'0b1010'
>>> bin(7)
'0b111'
>>> 

Note: The output of bin() has ‘0b’ in beginning which indicates that it is a binary number.

bool()

The bool() returns True when the argument x is True, False otherwise. The builtins True and False are the only two instances of the class bool.
Example

>>> bool(0)
False
>>> bool(5)
True
>>> bool('')
False
>>> bool(' ') 
True

chr()

The chr(i) return a Unicode string of one character with ordinal i
Example

>>> chr(97)
'a'
>>> chr(65)
'A'
>>> chr(92)
'\'
>>>  

dict()

The dict() function is use to create a dictionary having key and value pairs.
It creates empty dictionary if no parameters are passed.
Example

>>> dict([(1,2),(3,4),(5,6),(7,8),(9,10)])
{1: 2, 3: 4, 9: 10, 5: 6, 7: 8}
>>> dict()
{}
>>>   

dir()

The dir() function returns list of strings comprising of the attributes of the given objects. If called without an argument it returns the name with the current scope.
Example

>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__',  
>>> dir(str)
['__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', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

divmod()

The divmod() function takes two parameters and returns a tuple of their quotient and remainder i.e. it returns floor division and modulus of two numbers
Example

>>> divmod(5,11)
(0, 5)
>>> divmod(2,11)
(0, 2)
>>> divmod(11,2)
(5, 1)
>>> 

enumerate()

The enumerate() function takes two parameters (iterable, start) and returns iterator for index and value of iterable.
It returns an enumerate objects.
The enumerate object yields pairs containing a count (from start, which defaults to zero) and a value yielded by the iterable argument. enumerate is useful for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), …
Example

>>> for i in enumerate([10,20,30,40]):
	print(i)
(0, 10)
(1, 20)
(2, 30)
(3, 40) 
>>> for i in enumerate(['i','t','v','o','y','a','g','e','r','s'],1):
	print(i)
(1, 'i')
(2, 't')
(3, 'v')
(4, 'o')
(5, 'y')
(6, 'a')
(7, 'g')
(8, 'e')
(9, 'r')
(10, 's')
>>> 

eval()

The eval() function takes string as a argument which is parsed as expression.
Example

>>> eval('5*5')
25
>>> k=10
>>> eval('k-2')
8
>>> 

float()

The float() function is use to convert int, string and boolean value to float.
Example

>>> float(3)
3.0
>>> float('30')
30.0
>>> float(True)
1.0
>>> float(False)
0.0
>>>

help()

The help() function provides a helpful message when ‘help’ is typed at the Python interactive prompt. Calling help() at the Python prompt starts an interactive help session. Calling help(thing) prints help for the python object ‘thing’..
Example

>>> help(bin)
Help on built-in function bin in module builtins:

bin(...)
    bin(number) -> string
    
    Return the binary representation of an integer.
    
       >>> bin(2796202)
       '0b1010101010101010101010'

>>> help(ord)
Help on built-in function ord in module builtins:

ord(...)
    ord(c) -> integer
    
    Return the integer ordinal of a one-character string.

>>> 

hex()

The hex() function converts an integers to an hexadecimal numbers.
Example

>>> hex(10)
'0xa'
>>> hex(7)
'0x7'

Note: The output of hex() has ‘0x’ in beginning which indicates that it is a hexadecimal number.

id()

The id() function returns identity of an object i.e. object’s memory address.
Example

>>> a=5
>>> id(a)
2009780752
>>> id([1,2,3])==id([3,2,1])
True

input()

The input() function reads a line from shell as a string data type and it can be converted to desirable data type using type conversion.
Example

>>> a=input("Enter name")
Enter name Itvoyagers
>>> b=int(input("Enter a value"))
Enter a value50

int()

The int() function converts a number or string to an integer, or return 0 if no arguments are given.
Example

>>> int(3.2)
3
>>> int('2')
2

len()

The len() function returns a length of an object. It calculates whitespace as a character. len() cannot calculate length of integers.
Example

>>> len('54687')
5
>>> len('hello python')
12
>>> len([5,6,4])
3
>>> len(121)
Traceback (most recent call last):
  File "", line 1, in 
    len(121)
TypeError: object of type 'int' has no len()

list()

The list() function use to convert any compatible data type to list.
Example

>>> list({5,'k',6,'p'})
['k', 'p', 6, 5]
>>> list((5,'k',6,'p'))
[5, 'k', 6, 'p']
>>> list({1:'p',2:'h'})
[1, 2]
>>> 

min() and max()

The min() function returns the smallest item from the iterable.

The max() function returns the largest item from the iterable.
Example

>>> max([4,5,6])
6
>>> min([4,5,6])
4
>>> max(['A','B','a'])
'a'
>>> min(['A','B','a'])
'A'
>>> 

oct()

The oct() function converts an integers to an octal numbers.
Example

>>> oct(10)
'0o12'
>>> oct(7)
'0o7'
>>> 

Note: The output of oct() has ‘0o’ in beginning which indicates that it is a octal number.

pow()

The pow() function takes two argument x,y and returns x**y.
Example

>>> pow(24,0.5)
4.898979485566356
>>> pow(2,2)
4
>>> 

print()

It is the output function in python.
Example

>>> print("ITVoyagers")
ITVoyagers

str()

The str() function create a new string object from the given object.
Example

>>> str({5,'k',6,'p'})
"{'k', 'p', 6, 5}"
>>> str((5,'k',6,'p'))
"(5, 'k', 6, 'p')"
>>> str(552)
'552'
>>> str(9.5)
'9.5'

tuple()

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable’s items. If the argument is a tuple, the return value is the same object.
Example

>>> tuple([1,5,6])
(1, 5, 6)
>>> tuple('hello')
('h', 'e', 'l', 'l', 'o')
>>> tuple({1:2,3:4})
(1, 3)
>>> 

type()

The type() function returns datatype of a variable or a value. In python 2.x version type() returns and in python 3.x version type() returns
Example

>>> type(3.14)
<class 'float'>
>>> type(5)
<class 'int'="">
>>> type({5,8,9})
<class 'set'>
>>> type(30+2j)
<class 'complex'>
>>> 

sum()

sum(iterable, /, start=0) the sum of a ‘start’ value (default: 0) plus an iterable of numbers When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject non-numeric types.
Example

>>> sum([2,4,6,8])
20
>>> sum({1,2,3})
6

round()

round(number, ndigits=None) Round a number to a given precision in decimal digits. The return value is an integer if ndigits is omitted or None. Otherwise the return value has the same type as the number. ndigits may be negative.
Example

>>> round(5.6)
6
>>> round(5.4)
5
>>> round(5.5)
6

range()

The range() function Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, …, j-1. start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. These are exactly the valid indices for a list of 4 elements. When step is given, it specifies the increment (or decrement).
Example

>>> range(1,5)
range(1, 5)
>>> range(5)
range(0, 5)
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(range(1,5))
[1, 2, 3, 4]
>>> 

For other built-in functions like set (), reversed(), sorted(), complex() etc we can make use of help() on python shell to get detailed description of functions.

For other python basics related posts:

Best post on programming language and its types – 1
Python Programming (Basics) – History & Features
Python Programming (Basics)- Debugging & Types of errors
Python Programming (Basics) – Variables, Values, Types & Keywords.
Best post on built-in functions in python – 1
Python Programming (Basics) – Type Conversion
Python Programming (Basics) – Comments,Indentation,Built-in Number Data types and Expressions
Best post on IDLE & script mode in Python – 1
Python Programming (Basics)- Operators in Python
Best post on Order of Operations – Python
Simple and compound statements of python in easy way
Best post on conditional statements in python – Part 1
Best post on conditional statements in python – Part 2
Best post on looping in python (for loop)-Part 1
Best post on looping in python (while loop)-Part 2
Best post on nested loop in python(looping) -Part 3
Best post on infinite loop in python(looping) -Part 4
Best post on control statements(break,continue,pass)-1
Best post on Function definition & calling in python -1
Easy flow of function execution,parameters,arguments-2
Easy fruitful & void function,return values,stack diagrams-3
Best post on types of function arguments in python- 4
Best post on recursive function, scope of variable-5
Best post on import and from statement in python – 1
Best post on modules and built-in modules math,random & time-2
Best post on user defined modules in python-3
Best post on string datatype in python – 1
Best post immutable string,string operations python-2
Best post on string methods in python – 3
Best post on list datatype in python – 1
Best post on mutable list, list operations python – 2
Best post on List methods in python – 3
Best post on dictionary datatype in python – 1
Best post on dictionary methods and operations-2
Best post on tuple datatype in python – 1
Best post on tuple operations and immutable tuple- 2
Best post on tuple methods and built-in functions-3
17 -Python program to demonstrate Button in tkinter and its event in easy way
New posts coming soon.......



For other advanced python related posts:

File Systems and File Handling in Python
Types of file modes and attributes of file object in Python
How to read,write and append in a file in python?
Remaining file methods in Python
File Positions in Python
Directory in Python and its methods
Iterator and Iterables in Python
Exceptions in Python
Exception Handling in Python (Part I)
Exception Handling in Python (Part II)
Regular Expressions
Metacharacters or Regular Expression Patterns
Functions in 're' module(Part I)- Match vs Search
Functions in 're' module(Part II)-findall(), split(), sub()
Flags for regular expressions(Modifiers)
GUI programming in Python and Python GUI Library
What is Tkinter ?
Layout Manager (Geometry Manager) in Python
Events and Bindings in Python along with Widget configuration and styling
Fonts Names, Font Descriptors, System Fonts, Text formatting, Borders, Relief Styles in Python
Best post:Dimensions, Anchors, Bitmaps & Cursors in Python
Canvas widget of tkinter module – Python
Widgets in tkinter module – Python
Label, Text, Entry & Message Widget in Python
Button, Checkbutton & Radiobutton Widget in Python
Best post on Menu and Menubutton Widget of tkinter
Best post- Listbox and Scrollbar(Slider) Widget-Python
Best post on Frame Widget of tkinter in Python
Best post: message box widget and its methods
Best post- LabelFrame, Toplevel, PanedWindow widgets
Best post on Spinbox and Scale Widget in Python
Best post : Database connectivity in Python (Part 1)
Best post : Database Connectivity in Python (Part 2)
Best post on Create and Insert query : Python + MySQL
New posts coming soon.......

Leave a Comment