Python Built-in Functions Example

Python built-in functions are functions provided by python for you to use directly, such as print and input, etc. As of python version 3.6.2, a total of 68 built-in functions are provided. Today, let’s take a look at python’s built-in functions as shown in the figure below.

all python built in functions

1. Basic Data Types Functions.

1.1 Number Related Functions.

1.1.1 Data Type Convert Functions.
  1. bool():Convert a value to boolean data type. General False value are 0,””,{},[],(),False,None.

    >>> str = 'False'
    >>> bool(str)
    True
    >>> str = ''
    >>> bool(str)
    False
  2. int(): Convert a value to integer number.
    >>> int(3.5)
    3
    >>> int('6')
    6
  3. float(): Convert a value to float number.
    >>> float(3)
    3.0
    >>> float("3.500")
    3.5
1.1.2 Data Value Convert Functions.
  1. bin(): Convert to binary value that starts with 0b.
    >>> bin(10)
    '0b1010'
  2. Oct(): Convert to octal beginning with 0o.
    >>> oct(10)
    '0o12'
    >>> oct(0b10101)
    '0o25'
    >>> oct(0XA)
    '0o12'
  3. hex(): Convert to hex starts with 0x.
    >>> hex(10)
    '0xa'
    >>> hex(-1)
    '-0x1'
1.1.3 Mathematical Functions.
  1. abs (): returns the absolute value.
    >>> abs(-89)
    89
  2. divmod (a,b): returns a tuple which contains quotient and remainder.
    >>> divmod(10,3)
    (3, 1)
  3. round(a, b) : rounding a number with specified number position after the point. for example
    print(round(10/6,5))
    1.66667
  4. pow(a,b) : Find the b power of a, if there are three parameters. Then the third number is redundant after the power is obtained.
    >>> pow(2,3)
    8
  5. sum (iterable,start) : loop over an iterable object, calculates the summary value of each number item, the start is used to specify the begin index in the iterable object, the default value is 0 if omit.
    # Calculates the sum of two lists
    lst1=[2,3,4]
    lst2=[1,2,3,4]
    print(sum(lst1,sum(lst2)))
    19
  6. min () : evaluate the minimum value.
    >>> a = (1,6,5)
    >>> min(a)
    1
  7. max () : evaluate the maximum value.
    >>> max('jerry','Tom','Richard')
    'jerry'
    >>> max(5,10,3)
    10

1.2 Data Structure Related Functions.

1.2.1 List Related Functions.
  1. list() : Create a list based on provided list.
    >>> list(['java','python','c++'])
    ['java', 'python', 'c++']
    >>> list(('java','python','c++'))
    ['java', 'python', 'c++']
    >>> list('java')
    ['j', 'a', 'v', 'a']
  2. tuple() : Create a tuple based on provided tuple.
    >>> tuple('python')
    ('p', 'y', 't', 'h', 'o', 'n')
    >>> tuple(['python','java','c++'])
    ('python', 'java', 'c++')
    >>> tuple(('python','java','c++'))
    ('python', 'java', 'c++')
  3. reversed() : Reverse a sequence and return the iterator of the reversed sequence.
    >>> lst= [1,4,5,76,88]
    >>> it=reversed(lst)
    >>> print(it)
    <list_reverseiterator object at 0x105075748>
    >>> for item in it:
    ...    print(item)
    ... 
    88
    76
    5
    4
    1
    
  4. slice(): slice of the list.
    >>> lst= [1,4,5,76,88]
    >>> s = slice(1,3)
    >>> print(lst[s])
    [4, 5]
    >>> s = slice(3, len(lst))
    >>> lst[s]
    [76, 88]
    >>> s = slice(3)
    >>> lst[s]
    [1, 4, 5]
1.2.2 String Functions.
  1. str(): Create a string value.
    >>> str(100)
    '100'
    >>> str(1.2)
    '1.2'
    >>> str('hello')
    'hello'
  2. format() : Format output, specific data related, used to calculate various counts, actuarial, etc.
    >>> format(91,"b")
    '1011011'
    >>> format(97,"c")
    'a'
    >>> format(123456789,"e")#
    '1.234568e+08'
    >>> format(123456789,".2e")
    '1.23e+08'
    >>> format(0.2342,".3f")
    '0.234'
  3. bytes(): Converting string to byte value.
    >>> bytes('dev2qa.com',encoding="utf-8")
    b'dev2qa.com'
  4. bytearray() : Create a new byte array.
    >>> bytearray('dev2qa.com','utf-8')
    bytearray(b'dev2qa.com')
  5. memoryview(): View bytes in memory.
    >>> v = memoryview(b'abcefg')
    >>> print(v)
    <memory at 0x00DC9238>
    >>> print(list(v)) # [97, 98, 99, 101, 102, 103]
    [97, 98, 99, 101, 102, 103]
  6. ord(): Used to return ASCII value (0-255) or unicode numeric value of a single character.
    >>> ord('v')
    118
    >>> ord('1')
    49
    >>> ord(1)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: ord() expected string of length 1, but int found
    >>> ord('ab')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: ord() expected a character, but string of length 2 found
    >>>
  7. chr(): Enter an integer [0, 255] to return its corresponding ASCII symbol.
    >>> chr(1)
    '\x01'
    >>> chr(16)
    '\x10'
    >>> chr(100)
    'd'
    >>> chr('100')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: an integer is required (got type str)
  8. ascii() : Return a string value of the provided object, none ascii character will be escaped.
    >>> ascii('Pythön is interesting')
    "'Pyth\\xf6n is interesting'"
  9. repr() : Returns the string form of an object, which is the output of the original object, and neither quotation marks nor escape characters work.
    >>> list = ['a']
    >>> repr(list)
    "['a']"
1.2.3 Collection Data Functions.
  1. dict() : dictionary.
  2. Set (): Set elements are hashable, but they are not hashable in themselves and cannot be used as keys in dictionaries.
  3. Frozenset (): Create a frozen collection. The frozen collection cannot be added or deleted, and can be used as the key of a dictionary.
    >>> s = {'a','b','c'}
    >>>
    >>> dic = {s:"dev2qa.com"}
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unhashable type: 'set'
    >>>
    >>> ss=frozenset(s)
    >>>
    >>> dic = {ss:"dev2qa.com"}
    >>>
    >>> print(dic)
    {frozenset({'c', 'b', 'a'}): 'dev2qa.com'}
  4. len() : returns the number of elements in an object.
    >>> len('dev2qa.com')
    10
    >>> len(['dev2qa.com'])
    1
    >>> len(88888)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: object of type 'int' has no len()
    >>> len('88888')
    5
  5. sorted(): Sort iterable objects.
    >>> lst = [9,4,2,54,6,32,1]
    >>> print(sorted(lst))
    [1, 2, 4, 6, 9, 32, 54]
  6. enumerate() : Return the enumeration object of the collection, the return value type is tuple.
    >>> lst = ["java","python","ios"]
    >>> 
    >>> enu = enumerate(lst)
    >>> for el in enu: 
    ...    print(el) 
    ... 
    (0, 'java')
    (1, 'python')
    (2, 'ios')
    >>> enu = enumerate(lst)
    >>> for idx,el in enu:
    ...    print(idx,el)
    ... 
    0 java
    1 python
    2 ios
    >>> enu = enumerate(lst, 100)
    >>> for idx,el in enu:
    ...    print(idx, el)
    ... 
    100 java
    101 python
    102 ios
    >>>
  7. all() : When all of the iterable objects are True, then the result is True, similar to and operator.
    >>> all([False,'0','hello'])
    False
    >>> all([True,'0','hello'])
    True
    >>> all([True,'','hello'])
    False
  8. any() : One of the iterable objects is True, then the result is True, similar to or operator.
    >>> any([True,'','hello'])
    True
  9. zip() : Take iterable objects as a parameter, wrap the corresponding elements in the iterable object into a tuple, and then return those tuples. If the number of elements in each iterator object is inconsistent, the object with the shortest list length is returned.
    >>> lst =["Java","Python","iOS"]
    >>> lst2 =["Node","Android"]
    >>> lst3 =["MacOS","Linux","Windows"]
    >>> a = zip(lst,lst2,lst3)
    >>> print("__iter__" in dir(a)) 
    True
    >>> 
    >>> for el in a:
    ...    print(el) 
    ... 
    ('Java', 'Node', 'MacOS')
    ('Python', 'Android', 'Linux')
    >>> 
    
  10. filter(function,iterable) : Take out each element of the iterable object and run it with the provided function. The function return True or False. Only retain the element which function return True.
    >>> lst = [23, 28, 15, 27, 24, 22]
    >>> s = filter(lambda x: x >18 and x%2==0,lst)
    >>> print(s) 
    <filter object at 0x1079f0b38>
    >>> print(list(s))
    [28, 24, 22]
  11. map(function,iterable) : Take out each element of an iterable object and run it in function. The returned data is the result.
    >>> lst = [1,5,9,3]
    >>> m = map(lambda x:x**2,lst)
    >>> print(list(m))
    [1, 25, 81, 9]
    
    >>> lst1 = [1, 2, 3, 4, 5]
    >>> lst2 = [2, 4, 6, 8, 10]
    >>> m = map(lambda x,y:x+y,lst1,lst2)
    >>> print(list(m))  #[3, 6, 9, 12, 15]
    [3, 6, 9, 12, 15]

2. Scope Related Functions.

  1. locals () : returns the name within the current scope.
  2. globals (): returns the name in the global scope.
    >>> def test():
    ...     a=10
    ...     print(locals()) 
    ... 
    >>> test()
    {'a': 10}
    >>> 
    >>> print(globals())
    {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'lst': [1, 5, 9, 3], 'enu': <enumerate object at 0x1079f36c0>, 'el': ('Python', 'Android', 'Linux'), 'idx': 102, 'lst2': [2, 4, 6, 8, 10], 'lst3': ['MacOS', 'Linux', 'Windows'], 'a': <zip object at 0x1079f25c8>, 's': <filter object at 0x1079f0b38>, 'm': <map object at 0x1079f0c88>, 'lst1': [1, 2, 3, 4, 5], 'test': <function test at 0x1079d67b8>}
    >>> 
    >>> print(locals())
    {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'lst': [1, 5, 9, 3], 'enu': <enumerate object at 0x1079f36c0>, 'el': ('Python', 'Android', 'Linux'), 'idx': 102, 'lst2': [2, 4, 6, 8, 10], 'lst3': ['MacOS', 'Linux', 'Windows'], 'a': <zip object at 0x1079f25c8>, 's': <filter object at 0x1079f0b38>, 'm': <map object at 0x1079f0c88>, 'lst1': [1, 2, 3, 4, 5], 'test': <function test at 0x1079d67b8>}
    

3. Iterator/Generator Related Functions.

  1. range(): Used to generate numbers list for example.
    >>> for i in range(10):
    ...    print(i)
    ... 
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
  2. iter() : Get iterators, internally use the __iter__() method to get iterators.
  3. next() : Get next element with the iterator, internally using the __next__() method to return the iterator’s next item.
    >>> lst= ["Python","Java","Android"]
    >>> # get the iterator.
    ... it=iter(lst) # same as (lst.__iter__())
    >>> for i in it:
    ...   print(i)
    ...   it.__next__()
    ... 
    Python
    'Java'
    Android
    Traceback (most recent call last):
      File "<stdin>", line 3, in <module>
    StopIteration
    
    >>> lst= ["Python","Java","Android"]
    >>> # get the iterator.
    ... # same as (lst.__iter__())
    ... it=iter(lst)
    >>> for i in it:
    ...   print(i)
    ...   # same as (it.__next__())
    ...   # Add None to avoid StopIteration exception 
    ...   next(it, None) 
    ... 
    Python
    'Java'
    Android

4. Reflection Related Functions.

  1. hasattr(obj, str) : check whether obj contains str or not, return True or False.
  2. getattr(obj, str): get str value from obj.
  3. setattr(obj, str, value): set obj str value.
  4. delattr(obj, str) : delete str value from obj.
    >>> class Employee:
    ...   name = "Jerry"
    ...   age = 36
    ...   department = "Dev"
    ... 
    >>> hasattr(Employee, 'department')
    True
    >>> hasattr(Employee, 'salary')
    False
    
    >>> getattr(Employee, 'name')
    'Jerry'
    
    >>> setattr(Employee, 'age', '18')
    >>> getattr(Employee, 'age')
    '18'
    
    >>> delattr(Employee, 'department')
    >>> getattr(Employee, 'department')
    Traceback (most recent call last):
      File "", line 1, in 
    AttributeError: type object 'Employee' has no attribute 'department'
    

5. Object Oriented Functions.

  1. issubclass() : Determines whether the first argument is a subclass of the second argument.
    >>> class Animal:
    ...    pass
    ... 
    >>> class Bird(Animal):
    ...    pass
    ... 
    >>> class Duck(Bird):
    ...    pass
    ... 
    >>> class Dog(Animal):
    ...    pass
    ... 
    >>> 
    >>> issubclass(Bird, Animal)
    True
    >>> issubclass(Duck, Animal)
    True
    >>> issubclass(Dog, Bird)
    False
  2. type() : Get the data type of an object, it will return the class that create the object.
    >>> class Hello:
    ...    def show(self):
    ...        print("hello")
    ... 
    >>> obj=Hello()
    >>> 
    >>> print(obj,type(obj))
    <__main__.Hello object at 0x10312abe0> <class '__main__.Hello'>
    >>> type(obj)
    <class '__main__.Hello'>
    >>> type('hello')
    <class 'str'>
    >>> type(88)
    <class 'int'>
  3. isinstance() : Determine whether the object is of provided class type.
    >>> class Hello:
    ...    pass
    ... 
    >>> isinstance(Hello(), Hello)
    True
    >>> 
    >>> isinstance('hello', str)
    True
    >>> isinstance(8, int)
    True
    
  4. hash() : Get hash value of the provided object.
    hash('dev2qa.com')
    2973421833085428103
    
  5. id() : Get object memory address.
    >>> class Hello:
    ...    pass
    ... 
    >>> id(Hello)
    140396975939144
  6. help() : To see a function or module’s detail description.
  7. callable() : Checks whether an object is callable and the result is True or False.
    >>> def func():
    ...     pass
    ... 
    >>> callable(func())
    False
    >>> 
    >>> callable(func)
    True
  8. eval() : Executes python code in a string and return the final result.
    >>> n = input("Please input number :")
    Please input number :print(eval(n))
    >>> 1
    1
    >>> 2
    2
    
  9. exec() : Executes string-type code with no return value.
    >>> exec("a = 1+2+3")
    >>> print(a)
    6
  10. compile(resource, file_name, mode): Compile string-type code and the compile result object can be executed by exec() or evaluated by eval().
    resource : python code string.
    file_name: the python source code file name can be empty when resource is not empty.
    mode: the python source code type, value can be exec, eval or single. please look at the comments below for explanation.

    >>> code1 = "for i in range(3): print(i)"
    >>> # mode="exec" means the string contains process statements.
    ... c1 = compile(code1, "", mode="exec")
    >>> exec(c1)    
    0
    1
    2
    >>> 
    >>> code2 = "1+2+3"
    >>> # mode="eval" means the string contains value expression.
    ... c2 = compile(code2, "", mode="eval")
    >>> a = eval(c2)
    >>> print(a)
    6
    >>> 
    >>> 
    >>> code3 = "name = input('Input a number :')"
    >>> # mode="single" means the string code should be interact with user.
    ... c3 = compile(code3, "", mode="single")
    >>> exec(c3)
    Input a number :print(name) 1
    >>> 2
    2