68 Built-in Python Functions You Should Master!

Click the aboveβ€œBeginner’s Visual Learning” and choose to addStar or β€œTop”

Important content delivered to you promptly

Built-in functions are functions provided by Python that you can use directly, such as print, input, etc.

As of Python version 3.6.2, a total of 68 built-in functions are provided, listed as follows πŸ‘‡

abs()           dict()        help()         min()         setattr()
all()           dir()         hex()          next()        slice() 
any()           divmod()      id()           object()      sorted() 
ascii()         enumerate()   input()        oct()         staticmethod() 
bin()           eval()        int()          open()        str() 
bool()          exec()        isinstance()   ord()         sum() 
bytearray()     filter()      issubclass()   pow()         super() 
bytes()         float()       iter()         print()       tuple() 
callable()      format()      len()          property()    type() 
chr()           frozenset()   list()         range()       vars() 
classmethod()   getattr()     locals()       repr()        zip() 
compile()       globals()     map()          reversed()    __import__() 
complex()       hasattr()     max()          round() 
delattr()       hash()        memoryview()   set()

This article organizes these 68 built-in functions into 12 categories. Readers who are learning Python basics should not miss this; it’s recommended to bookmark it for study!

  • Related to Numbers

    • 1. Data Types

    • 2. Base Conversion

    • 3. Mathematical Operations

  • Related to Data Structures

    • 1. Sequences

    • 2. Data Collections

    • 3. Related Built-in Functions

  • Related to Scope

  • Related to Iterators and Generators

  • Execution of String Type Code

  • Input and Output

  • Related to Memory

  • File Operation Related

  • Module Related

  • Help

  • Related to Calls

  • View Built-in Attributes

Related to Numbers

1. Data Types

  • bool: Boolean (True, False)
  • int: Integer
  • float: Floating Point
  • complex: Complex Number

2. Base Conversion

  • bin(): Converts the given argument to binary
  • oct(): Converts the given argument to octal
  • hex(): Converts the given argument to hexadecimal

print(bin(10))  # Binary: 0b1010
print(hex(10))  # Hexadecimal: 0xa
print(oct(10))  # Octal: 0o12

3. Mathematical Operations

  • abs(): Returns the absolute value
  • divmod(): Returns the quotient and remainder
  • round(): Rounds to the nearest integer
  • pow(a, b): Computes a raised to the power of b. If a third parameter is given, it computes the modulus after exponentiation
  • sum(): Computes the sum
  • min(): Finds the minimum value
  • max(): Finds the maximum value

print(abs(-2))  # Absolute Value: 2
print(divmod(20, 3)) # Quotient and Remainder: (6, 2)
print(round(4.50))   # Rounding: 4
print(round(4.51))   # 5
print(pow(10, 2, 3))  # If a third parameter is provided, it indicates the final modulus: 1
print(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))  # Sum: 55
print(min(5, 3, 9, 12, 7, 2))  # Minimum Value: 2
print(max(7, 3, 15, 9, 4, 13))  # Maximum Value: 15

Related to Data Structures

1. Sequences

(1) Lists and Tuples

  • list(): Converts an iterable object to a list
  • tuple(): Converts an iterable object to a tuple

print(list((1, 2, 3, 4, 5, 6)))  #[1, 2, 3, 4, 5, 6]
print(tuple([1, 2, 3, 4, 5, 6]))  #(1, 2, 3, 4, 5, 6)

(2) Related Built-in Functions

  • reversed(): Reverses a sequence and returns an iterator of the reversed sequence
  • slice(): Slices a list

lst = "Hello"
it = reversed(lst)   # Does not change the original list. Returns an iterator, a design rule
print(list(it))  # ['o', 'l', 'l', 'e', 'H']
lst = [1, 2, 3, 4, 5, 6, 7]
print(lst[1:3:1])  #[2, 3]
s = slice(1, 3, 1)  # Used for slicing
print(lst[s])  #[2, 3]

(3) Strings

  • str(): Converts data to a string

print(str(123) + '456')  # 123456
  • format(): Related to specific data, used for calculations of various decimals, precision, etc.
s = "hello world!"
print(format(s, "^20"))  # Center aligned
print(format(s, "<20"))  # Left aligned
print(format(s, ">20"))  # Right aligned
#     hello world!    
# hello world!        
#         hello world!
print(format(3, 'b'))    # Binary: 11
print(format(97, 'c'))   # Converts to unicode character: a
print(format(11, 'd'))   # Decimal: 11
print(format(11, 'o'))   # Octal: 13 
print(format(11, 'x'))   # Hexadecimal (lowercase letters): b
print(format(11, 'X'))   # Hexadecimal (uppercase letters): B
print(format(11, 'n'))   # Same as d: 11
print(format(11))         # Same as d: 11
print(format(123456789, 'e'))      # Scientific notation, default keeps 6 decimal places: 1.234568e+08
print(format(123456789, '0.2e'))   # Scientific notation, keeps 2 decimal places (lowercase): 1.23e+08
print(format(123456789, '0.2E'))   # Scientific notation, keeps 2 decimal places (uppercase): 1.23E+08
print(format(1.23456789, 'f'))     # Decimal notation, keeps 6 decimal places: 1.234568
print(format(1.23456789, '0.2f'))  # Decimal notation, keeps 2 decimal places: 1.23
print(format(1.23456789, '0.10f'))  # Decimal notation, keeps 10 decimal places: 1.2345678900
print(format(1.23456789e+3, 'F'))   # Decimal notation, when very large outputs INF: 1234.567890
  • bytes(): Converts a string to bytes type
bs = bytes("Hello, are you eating today?", encoding="utf-8")
print(bs)  # b'\xe4\xbb\x8a\xe5\xa4\xa9\xe5\x90\x83\xe9\xa5\xad\xe4\xba\x86\xe5\x90\x97'
  • bytearray(): Returns a new byte array. The elements of this number are mutable, and each element’s value range is [0, 256)
ret = bytearray("alex", encoding='utf-8')
print(ret[0])  # 97
print(ret)  # bytearray(b'alex')
ret[0] = 65  # Assigns the value A to ret[0]
print(str(ret))  # bytearray(b'Alex')
  • ord(): Inputs a character to find its character encoding position

  • chr(): Inputs a position number to find the corresponding character
  • ascii(): Returns the value in ASCII code, otherwise returns u

print(ord('a'))  # The code position of letter a in the encoding table: 97
print(ord('δΈ­'))  # The position of 'δΈ­' in the encoding table: 20013
print(chr(65))  # Known code position, find out what the character is: A
print(chr(19999))  #丟

for i in range(65536):  # Print characters from 0 to 65535
    print(chr(i), end=" ")

print(ascii("@"))  #'@'
  • repr(): Returns the string form of an object
s = "Today I ate %s meals" % 3
print(s)  # Today I ate 3 meals
print(repr(s))   # Outputs as is, filtering out escape characters \n \t \r regardless of the percentage sign%
# 'Today I ate 3 meals'

2. Data Collections

  • Dictionary: dict creates a dictionary
  • Set: set creates a set

frozenset(): Creates a frozen set, which cannot be added to or deleted from.

3. Related Built-in Functions

  • len(): Returns the number of elements in an object
  • sorted(): Sorts an iterable object (lambda)

Syntax: sorted(Iterable, key=function (sorting rule), reverse=False)

  • Iterable: An iterable object
  • key: Sorting rule (sorting function), in sorted, each element of the iterable is passed to this function’s parameter. Sorts based on the result of the function’s operation
  • reverse: Whether it is in reverse order. True: reverse, False: normal order

lst = [5, 7, 6, 12, 1, 13, 9, 18, 5]
lst.sort()  # sort is a method inside list
print(lst)  #[1, 5, 5, 6, 7, 9, 12, 13, 18]

ll = sorted(lst) # Built-in function. Returns a new list that is sorted
print(ll)  #[1, 5, 5, 6, 7, 9, 12, 13, 18]

l2 = sorted(lst, reverse=True)  # Reverse order
print(l2)  #[18, 13, 12, 9, 7, 6, 5, 5, 1]
# Sort the list based on string length
lst = ['one', 'two', 'three', 'four', 'five', 'six']
def f(s):
    return len(s)
l1 = sorted(lst, key=f)
print(l1)  # ['one', 'two', 'six', 'four', 'five', 'three']
  • enumerate(): Gets the enumeration object of the collection
lst = ['one', 'two', 'three', 'four', 'five']
for index, el in enumerate(lst, 1):    # Gets the index and element together, index defaults to start from 0. Can be changed
    print(index)
    print(el)
# 1
# one
# 2
# two
# 3
# three
# 4
# four
# 5
# five
  • all(): All elements in the iterable must be True for the result to be True
  • any(): If any one of the elements in the iterable is True, the result is True

print(all([1, 'hello', True, 9]))  # True
print(any([0, 0, 0, False, 1, 'good']))  # True
  • zip(): This function takes iterable objects as parameters, packs corresponding elements from the objects into a tuple, and returns a list composed of these tuples. If the number of elements in the iterators is inconsistent, the length of the returned list is the same as the shortest object

lst1 = [1, 2, 3, 4, 5, 6]
lst2 = ['Song of the Drunken Country', 'The Donkey Gets Water', 'The Class of the Cowherd in Spring', 'A Beautiful Life', 'The Defender', 'The Life of Matsuko Who Was Disliked']
lst3 = ['USA', 'China', 'France', 'Italy', 'South Korea', 'Japan']
print(zip(lst1, lst1, lst3))  # <zip 0x00000256ca6c7a88="" at="" object="">
for el in zip(lst1, lst2, lst3):
    print(el)
# (1, 'Song of the Drunken Country', 'USA')
# (2, 'The Donkey Gets Water', 'China')
# (3, 'The Class of the Cowherd in Spring', 'France')
# (4, 'A Beautiful Life', 'Italy')
# (5, 'The Defender', 'South Korea')
# (6, 'The Life of Matsuko Who Was Disliked', 'Japan')
</zip>
  • filter(): Filters (lambda)

Syntax: filter(function, Iterable)

function: A function used for screening. In filter, elements in the iterable are automatically passed to the function. Then based on whether the function returns True or False, it decides whether to keep this data.

def func(i):    # Determines odd numbers
    return i % 2 == 1
    lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
l1 = filter(func, lst)  # l1 is an iterator
print(l1)  # <filter 0x000001ce3ca98ac8="" at="" object="">
print(list(l1))  #[1, 3, 5, 7, 9]
</filter>
  • map(): Maps the specified sequence according to the provided function (lambda)

Syntax: map(function, iterable)

Can map each element in the iterable object. It executes the function for each element separately.

def f(i):    
  return i
  lst = [1, 2, 3, 4, 5, 6, 7, ]
it = map(f, lst) # Passes each element in the iterable object to the previous function for processing. The results will be returned as an iterator
print(list(it))  #[1, 2, 3, 4, 5, 6, 7]

Related to Scope

  • locals(): Returns names in the current scope
  • globals(): Returns names in the global scope
def func():
    a = 10
    print(locals())  # Contents of the current scope
    print(globals())  # Contents of the global scope
    print("Today there is a lot of content")
func()
# {'a': 10}
# {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': 
# <_frozen_importlib_external.SourceFileLoader object at 0x0000026F8D566080>, 
# '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins'="" (built-in)="">, '__file__': 'D:/pycharm/Practice/week03/new14.py', '__cached__': None,
# 'func': <function 0x0000026f8d6b97b8="" at="" func="">}
# Today there is a lot of content
</function></module>

Related to Iterators and Generators

  • range(): Generates data
  • next(): The iterator executes down once, internally actually uses the __next__() method to return the next item of the iterator
  • iter(): Gets the iterator, internally actually uses the __iter__() method to get the iterator
for i in range(15, -1, -5):
    print(i)
# 15
# 10
# 5
# 0
lst = [1, 2, 3, 4, 5]
it = iter(lst)  # __iter__() to get the iterator
print(it.__next__())  # 1
print(next(it))  # 2  __next__()  
print(next(it))  # 3
print(next(it))  # 4

Execution of String Type Code

  • eval(): Executes string type code and returns the final result
  • exec(): Executes string type code
  • compile(): Encodes string type code. The code object can be executed by the exec statement or evaluated by eval()
s1 = input("Please enter a+b:")  # Input: 8+9
print(eval(s1))  # 17 Can dynamically execute code. The code must have a return value
s2 = "for i in range(5): print(i)"
a = exec(s2) # exec executes code and returns nothing

# 0
# 1
# 2
# 3
# 4
print(a)  # None

# Dynamically execute code
exec("""
def func():
    print(" I am Jay Chou")
""" )
func()  # I am Jay Chou

code1 = "for i in range(3): print(i)"
com = compile(code1, "", mode="exec")   # compile does not execute your code, it just compiles
exec(com)   # Execute the compiled result
# 0
# 1
# 2

code2 = "5+6+7"
com2 = compile(code2, "", mode="eval")
print(eval(com2))  # 18

code3 = "name = input('Please enter your name:')"  # Input: hello
com3 = compile(code3, "", mode="single")
exec(com3)
print(name)  # hello

Input and Output

  • print(): Prints output
  • input(): Gets user output content
print("hello", "world", sep="*", end="@") # sep: what to use to connect the printed content, end: what to use as the end
# hello*world@

Related to Memory

  • hash(): Gets the hash value of an object (int, str, bool, tuple). Hash algorithm: (1) The purpose is uniqueness (2) dict lookup efficiency is very high, hash table. Uses space to exchange time, which is relatively memory-intensive
s = 'alex'
print(hash(s))  #-168324845050430382
lst = [1, 2, 3, 4, 5]
print(hash(lst))  # Error, list is unhashable
  id():  Gets the memory address of the object
s = 'alex'
print(id(s))  # 2278345368944

File Operation Related

  • open(): Used to open a file, creating a file handle
f = open('file', mode='r', encoding='utf-8')
f.read()
f.close()

Module Related

__import__(): Used for dynamically loading classes and functions

# Let the user input a module to import
import os
name = input("Please enter the module you want to import:")
__import__(name)    # Can dynamically import modules

Help

  • help(): Function used to view the detailed description of the function or module
print(help(str))  # View the usage of strings

Related to Calls

  • callable(): Used to check if an object is callable. If it returns True, the object may fail to call, but if it returns False, then the call will definitely fail
a = 10
print(callable(a))  # False  Variable a cannot be called
#
def f():
    print("hello")
    print(callable(f))   # True Function can be called

View Built-in Attributes

  • dir(): View the built-in attributes of an object, accesses the object’s __dir__() method

print(dir(tuple))  # View methods of tuples



Download 1: OpenCV-Contrib Extended Module Chinese Tutorial

Reply "Extended Module Chinese Tutorial" in the background of the "Beginner's Visual Learning" official account to download the first OpenCV extended module tutorial in Chinese, covering installation of extended modules, SFM algorithms, stereo vision, target tracking, biological vision, super-resolution processing, and more than twenty chapters of content.

Download 2: 52 Lectures on Practical Python Vision Projects

Reply "Python Vision Practical Projects" in the background of the "Beginner's Visual Learning" official account to download 31 practical vision projects including image segmentation, mask detection, lane line detection, vehicle counting, eyeliner addition, license plate recognition, character recognition, emotion detection, text content extraction, and face recognition to help quickly learn computer vision.

Download 3: 20 Lectures on Practical OpenCV Projects

Reply "20 Lectures on Practical OpenCV Projects" in the background of the "Beginner's Visual Learning" official account to download 20 practical projects based on OpenCV, achieving advanced learning in OpenCV.

Group Chat

Welcome to join the official account reader group to communicate with peers. Currently, there are WeChat groups for SLAM, 3D vision, sensors, autonomous driving, computational photography, detection, segmentation, recognition, medical imaging, GAN, algorithm competitions, etc. (will gradually be subdivided in the future). Please scan the WeChat number below to join the group, with a note: "nickname + school/company + research direction", for example: "Zhang San + Shanghai Jiao Tong University + Visual SLAM". Please follow the format; otherwise, you will not be approved. After successful addition, you will be invited to join related WeChat groups based on research direction. Please do not send advertisements in the group; otherwise, you will be removed from the group. Thank you for your understanding~


Leave a Comment