The use and classification of 68 built-in functions in Python

Foreword

Functions built into the Python interpreter that can be used directly. These functions require no additional imports or installation and can be called directly from Python code. Python’s built-in functions include many commonly used functions, such as operations on data types, mathematical operations, string processing, file operations, etc. Some common built-in functions include print(), len(), input(), range(), open(), etc. These built-in functions provide Python programmers with convenient and fast ways to complete various tasks. As of python version 3.6.2, a total of 68 built-in functions are provided, which are summarized 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() ?lter() issubclass() pow() super()
bytes() ?oat() 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 comprehensively organizes these 68 built-in functions into 12 categories. Readers who are learning the basics of Python must not miss it. It is recommended to collect and learn!

Related to numbers

1. Data type

  • bool: Boolean type (True, False)

  • int: integer type (integer)

  • float: floating point type (decimal)

  • complex : plural

2. Base conversion

  • bin() converts the given parameters into binary

  • oct() converts the given parameters into octal

  • hex() converts the given parameters into hexadecimal

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

3. Mathematical operations

  • abs() returns the absolute value

  • divmode() returns the quotient and remainder

  • round() rounds

  • pow(a, b) finds the power b of a. If there are three parameters. After calculating the power, take the remainder of the third number.

  • sum() sum

  • min() finds the minimum value

  • max() finds the maximum value

print(abs(-2)) # Absolute value: 2
print(divmod(20,3)) # Find the quotient and remainder: (6,2)
print(round(4.50)) # Rounding: 4
print(round(4.51)) #5
print(pow(10,2,3)) # If the third parameter is given, it means the final remainder: 1
print(sum([1,2,3,4,5,6,7,8,9,10])) # Sum: 55
print(min(5,3,9,12,7,2)) #Find the minimum value: 2
print(max(7,3,15,9,4,13)) #Find the maximum value: 15

Related to data structure

1. Sequence

(1) Lists and tuples

  • list() converts an iterable object into a list

  • tuple() converts an iterable object into 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() slice of list

lst = "Hello"
it = reversed(lst) # Will not change the original list. Returns an iterator, a design rule
print(list(it)) #['Ah', 'Okay', 'You']
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) String

  • str() converts data into string

print(str(123) + '456') #123456
  • format() is related to specific data and is used to calculate various decimals, actuarial calculations, etc.

s = "hello world!"
print(format(s, "^20")) #In the play
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' )) # Convert to unicode character: a
print(format(11, 'd' )) #? Base: 11
print(format(11, 'o' )) # Octal: 13
print(format(11, 'x' )) # Hexadecimal (?write 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. 6 decimal places are retained by default: 1.234568e + 08
print(format(123456789, '0.2e' )) # Scientific notation. Keep 2 decimal places (lowercase): 1.23e + 08
print(format(123456789, '0.2E' )) # Scientific notation. Keep 2 decimal places (uppercase): 1.23E + 08
print(format(1.23456789, 'f' )) # Decimal point counting method. Keep 6 decimal places: 1.234568
print(format(1.23456789, '0.2f' )) # Decimal point counting method. Keep 2 decimal places: 1.23
print(format(1.23456789, '0.10f')) # Decimal point counting method. Keep 10 decimal places: 1.2345678900
print(format(1.23456789e + 3, 'F')) # Decimal point counting method. When it is very large, output INF:1234.567890
  • bytes() converts string into bytes type

bs = bytes("Have you eaten 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 the value range of each element is [0,256)

ret = bytearray("alex" ,encoding ='utf-8')
print(ret[0]) #97
print(ret) #bytearray(b'alex')
ret[0] = 65 #Assign the value of position A of 65 to ret[0]
print(str(ret)) #bytearray(b'Alex')
  • ord() input characters to find the position with character encoding

  • chr() Enter the position number to find the corresponding character

  • ascii() returns the value in ascii code, otherwise it returns u

print(ord('a')) # The code point of letter a in the encoding table: 97
print(ord('中')) # The position of '中' in the encoding table: 20013
print(chr(65)) # Given the code point, find out what the character is: A
print(chr(19999)) #lost

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

print(ascii("@")) #'@'
  • repr() returns the string form of an object

s = "Today\\
I had %s meals\t" % 3
print(s)#Today# I had 3 meals
print(repr(s)) # Output as is, filter out escape characters \\
 \t \r Regardless of the percent sign %
#'Today\\
I had 3\t meals'

2. Data collection

  • Dictionary: dict creates a dictionary

  • Collection: set creates a collection

frozenset() creates a frozen set. Frozen sets cannot be added or deleted.

3. Related built-in functions

  • len() returns the number of elements in an object

  • sorted() performs sorting operations on iterable objects (lamda)

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

  • Iterable: iterable object

  • key: Sorting rule (sorting function), internally in sorted each element in the iterable object will be passed to the parameter of this function. Sort according to the result of the function operation

  • reverse: whether it is a flashback. True: flashback, False: forward sequence

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

ll = sorted(lst) # Built-in function. Returns you a new list. The new list 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 according to 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): # Get the index and the element together. The index starts from 0 by default. It can be changed.
    print(index)
    print(el)
# 1
# one
# 2
#two
#3
#three
#4
# four
#5
# five
  • all() The iterable object is all True, and the result is True

  • If one of the any() iterable objects is True, the result is True

print(all([1,'hello',True,9])) #True
print(any([0,0,0,False,1,'good'])) #True
  • The zip() function is used to take an iterable object as a parameter, pack the corresponding elements in the object into a tuple, and then return a list composed of these tuples. If the number of elements in each iterator is inconsistent, the length of the list is returned Same as the shortest object

lst1 = [1, 2, 3, 4, 5, 6]
lst2 = ['Drunk Country Ballads', 'Donkey Gets Water', 'Spring in the Cowherd Class', 'Beautiful Life', 'Defender', 'The Life of the Disliked Songzi\ ']
lst3 = ['United States', 'China', 'France', 'Italy', 'Korea', 'Japan']
print(zip(lst1, lst1, lst3)) #<zip object at 0x00000256CA6C7A88>
for el in zip(lst1, lst2, lst3):
    print(el)
# (1, 'Drunk Country Folk', 'America')
# (2, 'Donkey gets water', 'China')
# (3, 'Spring of the Cowherd', 'France')
# (4, 'Beautiful Life', 'Italy')
# (5, 'Defender', 'Korea')
# (6, 'The life of the despised Matsuko', 'Japan')
  • fiter() filter (lamda)

Syntax: fiter(function.Iterable)

function: function used for filtering. In ?lter, the elements in iterable are automatically passed to function. Then based on the True or False returned by the function, it is judged whether to retain this data. Iterable: iterable object

def func(i): # Determine odd number
    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 object at 0x000001CE3CA98AC8>
print(list(l1)) #[1, 3, 5, 7, 9]
  • map() will map the specified sequence column according to the provided function (lamda)

Syntax: map(function, iterable)

Each element in the iterable object can be mapped. Execute the function separately

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

Related to scope

  • locals() returns the names in the current scope

  • globals() returns names in the global scope

def func():
    a=10
    print(locals()) # Contents in the current scope
    print(globals()) # Contents in global scope
    print("There is a lot of content today")
fun()
# {'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 func at 0x0000026F8D6B97B8>}
# Today there is a lot of content

Related to iterator generators

  • range() generates data

  • next() the iterator executes downward once, and the __next__() method is actually used internally to return the next item of the iterator

  • iter() obtains the iterator. The __ iter__() method is actually used internally to obtain 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__() gets 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 code of string type. Code objects can be executed through the exec statement or evaluated with eval()

s1 = input("Please enter a + b:") #Input: 8 + 9
print(eval(s1)) # 17 The code can be executed dynamically. The code must have a return value
s2 = "for i in range(5): print(i)"
a = exec(s2) # exec execution code does not return anything

#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 compilation 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(): print output

  • input(): Get the content output by the user

print("hello", "world", sep="*", end="@") # sep: what to connect the printed content with, end: what to end with
#hello*world@

Memory related

  • hash(): Get the hash value of the object (int, str, bool, tuple). Hash algorithm: (1) The purpose is uniqueness (2) dict search efficiency is very high, hash table. It is more time-consuming to exchange space Memory

s = 'alex'
print(hash(s)) #-168324845050430382
lst = [1, 2, 3, 4, 5]
print(hash(lst)) #Error, the list is not hashable
  id(): Get the memory address of the object
s = 'alex'
print(id(s)) #2278345368944

File operation related

  • open(): used to open a file and create a file handle

f = open('file',mode='r',encoding='utf-8')
f.read()
f.close()

Module related

__import__(): used to dynamically load classes and functions

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

Help

  • help(): function is used to view detailed descriptions of the purpose of a function or module

print(help(str)) #View the purpose of string

Call related

  • callable(): used to check whether an object is callable. If True is returned, the object may fail to call, but if False is returned, the call will never succeed.

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 properties

  • dir(): View the built-in properties of the object, accessing the __dir__() method in the object

print(dir(tuple)) #How to view tuples

Summary

You need to pay attention to the following points when using Python built-in functions:

  1. Proficiency in commonly used built-in functions, such as print(), input(), len(), range(), etc., can improve coding efficiency.

  2. Learn the functionality and usage of each built-in function.

  3. Flexible use of built-in functions can simplify code logic and improve code readability and maintainability.

  4. Pay attention to the parameters and return values of built-in functions, as well as possible exceptions, to ensure correct and safe use.

  5. Try to avoid reinventing the wheel and make good use of Python’s built-in functions and standard libraries to complete coding tasks faster.

In short, mastering the use of Python’s built-in functions and flexibly applying them to actual coding can improve coding efficiency and code quality.