Python built-in functions

Keywords: Python

Serial numberfunctionexplain
1abs()Returns the absolute value of a number
2divmod()Returns a tuple containing quotient and remainder, (quotient, remainder)
3max()Returns the maximum value of the given parameter
4min()Returns the minimum value of the given parameter
5pow(x,y)Returns the value of x to the power of y
6reduce()Accumulate the elements in the parameter sequence
7round(x)Returns the rounded value of a floating-point number x
8sum()Sum the parameters
9len()Returns the length of an object (character, list, tuple) or the number of elements
10Filter (function, sequence)Filter out unqualified elements
11Map (function, list)The function is applied to each element of the list in turn
12iter()Used to generate iterators
13next()Returns the next item of the iterator
14input()Accept a standard input data and return String type
15open()Used to open a file
16print()For printout
17range()You can create a list of integers
18slice()Implementing slice objects
19sorted()Sort (default ascending) all iteratable objects
20zip()It is used to take the iteratable object as a parameter and package the corresponding elements in the object into tuples
21__ import __()Used to dynamically load classes and functions
22list()Convert tuples to lists
23int()Converts a string or number to an integer
24bytearray()Returns a new byte array with variable elements in the group
25dict()Convert tuple / list to dictionary format
26enumerate()Combine a traversable object into an index sequence
27format()format string
28float()Converts integers and strings to floating point numbers
29repr()Convert the object into a form for the interpreter to read, and return the string format of an object.
30reversed()Returns an inverted iterator
31frozenset()Returns a frozen collection (an unordered sequence of non repeating elements)
32set()Create an unordered set of non repeating elements
33str()Convert object to String format
34tuple()Convert list to tuple
35all()Are all elements True
36any()Are all elements False
37bool()If the parameter is not null or 0, return True
38calllable()Check whether an object is callable. Yes
39hasattr()Judge whether the object contains corresponding attributes
40Isinstance (object, type)It is True to judge whether an object is a known type
41issubclass(class,classinfo)Judge whether class is a subclass of classinfo. It is True
42dir()Return method list
43globals()Returns all global variables
44help()Use to view a detailed description of the purpose of a function or module
45id()Gets the memory address of the object
46type()Returns the type of the parameter
47bin()Returns the binary of an integer
48oct()Returns the octal of an integer
49hex()Returns the hexadecimal value of an integer
50hash()Used to get the hash value of an object (number or string)
51chr()Returns the ASCII value corresponding to 0-255
52ord()Returns an ASCII numeric value corresponding to one character

Noun introduction

1 ° iterator

An iterator is an object with a next() method and is not counted by index. When the next item is required by using a loop mechanism, the next() method of the iterator is called, and a StopIteration exception is thrown after the iteration. Iterators can only move backward, cannot go back to the beginning, and iterate again can only create another new iteration object. reversed() returns an iterator accessed in reverse order.

1.abs()

abs(): returns the absolute value of the value

abs(-1)
## Out[1]: 1

2.divmod()

divmod(a,b): returns a tuple containing quotient and remainder (A / / B, a% B)

divmod(13,2)  ## Real number operation
## Out[1]: (6, 1)

3.max()

Returns the maximum value of a given parameter according to ASCII code. (a-z: 97-122,A-Z: 65-90,0-9: 48-57)

str_e = '1,2,3,4'
max(str_e)  ## 1. Compare the maximum value of the string
## Out[1]: '4'

list_e = [1,2,3,4]
max(list_e)  ## 2. Compare the maximum value of list elements
## Out[2]: 4

tup_e = ((1,2),(2,3),(3,4),(3,5))
max(tup_e)  ## 3. Compare the maximum value of tuple elements. Compare the first element first and the second element in the same case
## Out[3]: (3, 5)

dic_e = {1:1,2:1,3:1,4:1} 
max(dic_e)  ## 4. Compare the maximum value of dictionary elements, compare key values, and output the maximum key value
## Out[4]: 4

4.min()

Returns the minimum value of a given parameter according to ASCII code. (a-z: 97-122,A-Z: 65-90,0-9: 48-57)

str_e = '1,2,3,4'
min(str_e)  ## 1. Compare the minimum value of the string. The ASCII code value of the comma is 44
## Out[1]: ','

list_e = [1,2,3,4]
min(list_e)  ## 2. Compare the minimum values of list elements
## Out[2]: 1

tup_e = ((1,2),(2,3),(3,4),(3,5))
min(tup_e)  ## 3. Compare the minimum value of tuple elements. Compare the first element first and the second element in the same case
## Out[3]: (1, 2)

dic_e = {1:5,2:5,3:5,4:5} 
min(dic_e)  ## 4. Compare the minimum value of dictionary elements, compare key values, and output the minimum key value
## Out[4]: 1

5.pow(x,y)

Returns the y power of x.

(1) Reference math module

import math
math.pow(2,3)  ## Calculate the third power of 2
## Out[1]: 8.0

(2) Built in function

pow(x, y[, z]): calculate the Y power of X. if z exists, then take the module of the result, and the result is equivalent to pow (x, y)% z
Note: pow() is called directly through the built-in method. The built-in method will take the parameter as an integer, while the math module will convert the parameter to float

pow(2,3)  ## Calculate the third power of 2
## Out[2]: 8

pow(2,3,3)  ## After calculating the third power of 2, take the remainder of 3
## Out[3]: 2

6.reduce()

reduce(function, iterable[, initializer]): accumulate the elements in the parameter sequence through the function.

  • Function – function with two parameters
  • Iteratable – iteratable object
  • initializer – optional, initial parameter
from functools import reduce
def add(x, y):
    return x + y
sum1 = reduce(add, [1,2,3,4,5])   # Calculation list and: 1 + 2 + 3 + 4 + 5
sum1
## Out[1]: 15

sum2 = reduce(lambda x, y: x+y, [1,2,3,4,5])  # Using lambda anonymous functions
sum2
## Out[2]: 15

sum3 = reduce(lambda x, y: x+y, [1,2,3,4,5],3)  # The initial value is 3,3 + 1 + 2 + 3 + 4 + 5
sum3
## Out[2]: 18

7.round()

Round (x [, n]): returns the rounded value of floating point number x, where n is the number of decimal places.

round(22.2222,2)  ## Returns 22.2222 rounded value with 2 decimal places
## Out[1]: 22.22

8.sum()

sum(iterable[, start]): sum the sequence.

  • Iteratable – iteratable objects, such as lists, tuples, and collections.
  • start – specifies the addition parameter. If this value is not set, it defaults to 0.
sum([1,2,3,4,5])  ## Sum list
## Out[1]: 15

sum([1,2,3,4,5],6)  ## Add 6 after summing the list
## Out[2]: 21

9.len()

len(s): returns the length of an object (character, list, tuple, etc.) or the number of items.

str_e = 'ERROR'
len(str_e)
## Out[1]: 5

list_e = [1,2,3,4,5,6]
len(list_e)
## Out[2]: 6

10.filter()

filter(function, iterable): used to filter sequences, filter out unqualified elements, and return an iterator object.

## Returns an odd number
def is_odd(n):
    return n % 2 == 1

tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
tmplist
## Out[1]: <filter at 0x204ca295488>

list(tmplist)
## Out[2]: [1, 3, 5, 7, 9]

11.map()

map(function, iterable,...): map the specified sequence according to the provided function and return the iterator.

map(lambda x:x**2,[1,2,3,4,5])  ## Calculates the square of each element in the list and returns an iterator
## Out[1]: <map at 0x231e1bee108>

list(map(lambda x:x**2,[1,2,3,4,5]))
## Out[2]: [1, 4, 9, 16, 25]

12.iter()

iter(object[, sentinel]): used to generate iterators. If the second parameter is passed, the parameter object must be a callable object (such as a function). At this time, iter creates an iterator object and calls the iterator object every time__ next__ () method, object will be called.

list_e = [1,2,3,4,5]
for i in iter(list_e):
    print(i)
## Out[1]: 1 2 3 4 5

13.next()

next(iterable[, default]): returns the next item of the iterator. Default is optional. It is used to set the default value returned when there is no next element. If it is not set and there is no next element, a StopIteration exception will be triggered.

it = iter([1, 2, 3, 4, 5])
while True:
    try:
        x = next(it)  ## Get next value
        print(x)
    except StopIteration:
        break  ## Exit the loop when StopIteration is encountered
## Out[1]: 1 2 3 4 5

14.input()

Input ([prompt]): accept a standard input data and return it as string type. Raw in Python 3. X_ Input () and input () are integrated to remove raw_input() only retains the input() function, which receives arbitrary input, defaults all inputs to string processing, and returns string type.

name = input("Please enter user name:")
password = input("Please input a password:")
print("user name:"+name)
print("password:"+password)
## Out[1]: Please enter user name: ERROR
##         Please enter the password: error
##         User name: ERROR
##         Password: error

15.open()

open(): used to open a file and create a file object, and then the related methods can call it for reading and writing.

(1) Open mode

(2) file object method

methoddescribe
file.close()Close the file. After closing, the file can no longer be read or written.
file.flush()Refresh the internal buffer of the file and directly write the data of the internal buffer to the file immediately, rather than passively waiting for the output buffer to be written.
file.fileno()Returns an integer file descriptor (FD integer), which can be used for some underlying operations, such as the read method of the os module.
file.isatty()Returns True if the file is connected to a terminal device, False otherwise.
file.next()Returns the next line of the file.
file.read([size])Reads the specified number of bytes from the file. If not given or negative, all bytes are read.
file.readline([size])Read the entire line, including the "\ n" character.
file.readlines([sizeint])Read all rows and return the list. If sizeint > 0 is given, set the number of bytes read at a time to reduce the reading pressure.
file.seek(offset[, whence])Sets the current location of the file.
file.tell()Returns the current location of the file.
file.truncate([size])Intercept the file. The intercepted bytes are specified by size. The default is the current file location.
file.write(str)Writes a string to a file and returns the length of the written character.
file.writelines(sequence)Write a list of sequence strings to the file. If line breaks are required, add the line breaks of each line yourself.

Create a text.txt file

f = open('test.txt')
f.readlines()
## Out[1]: ['ERROR\n', 'error']

16.print()

print(*objects, sep = '', end = '\ n', file=sys.stdout, flush=False): used for printout.

  • Objects – plural number, indicating that multiple objects can be output at one time. When outputting multiple objects, you need to separate them with.
  • sep – used to separate multiple objects. The default value is a space.
  • End – used to set what to end with. The default value is newline \ n, we can replace it with other strings.
  • File – the file object to write to.
  • Flush – whether the output is cached is usually determined by file, but if the flush keyword parameter is True, the stream will be forced to refresh.
print("www","baidu","com",sep=".")  # Set spacer
## Out[1]: www.baidu.com

print("www","baidu","com",sep=".",end='..')  # Set Terminator
## Out[2]: www.baidu.com..

17.range()

range(start, stop[, step]): returns an iteratable object from start to stop (excluding stop) in steps of step.

list(range(0,10,2))
## Out[1]: [0, 2, 4, 6, 8]

18.slice()

slice(start, stop[, step]): parameter transfer used in slice operation function.

myslice = slice(1,6,1)    # Set the slice to intercept 5 elements
## myslice = slice(5)
arr = list(range(10))
arr[myslice]
## Out[1]: [1, 2, 3, 4, 5]

19.sorted()

The difference between sort and sorted

When the sorted() function is called, it provides a new ordered (default ascending) list as the return value. The original order of sort() is modified.

sorted()

(1) Simple sorting of lists, tuples, sets, strings
num = [2,1,9,5]
sorted(num)  ## 1. Sort the list
## Out[1]: [1, 2, 5, 9]

num_tup = (2,1,9,5)
sorted(num_tup)  ## 2. Sort tuples
## Out[2]: [1, 2, 5, 9]

num_set = {2,2,1,9,5}
sorted(num_set)  ## 3. Sort the set
## Out[3]: [1, 2, 5, 9]

num_str = 'I like to sort'
sorted(num_str)  ## 4. The sorted () function takes a str as a list, traverses each element (each character) in it, and sorts it according to ASCII code
## Out[4]: [' ', ' ', ' ', 'I', 'e', 'i', 'k', 'l', 'o', 'o', 'r', 's', 't', 't']
(2) Parameter reverse

reverse = True: descending
reverse = False: ascending

num = [2,1,9,5]
sorted(num,reverse=True)  ## Sort the list in descending order
## Out[5]: [9, 5, 2, 1]
(3) Parameter key

The key parameter can receive a function that will act on each value in the sorting list to determine the order of the results.

num_str = ['I','like','to','sort']
sorted(num_str)  ## Sort the strings in the list according to the ASCII value of the first character of the string
## Out[6]: ['I', 'like', 'sort', 'to']

sorted(num_str,key=len)  ## Sort in ascending order according to the length of the string
## Out[7]: ['I', 'to', 'like', 'sort']

num_str1 = ['I','i','like','Like']
sorted(num_str1,key=str.lower)  ## Sorts strings regardless of case (to lowercase)
## Out[8]: ['I', 'i', 'like', 'Like']

words = ['cba','acb','bac']
sorted(words,key=lambda x:x[::-1])  ##Sort according to the last character of the string
## Out[9]: ['cba', 'acb', 'bac']

sort()

sort is a method of the list class and can only be used with list.

num = [2,1,9,5]
num.sort()
num
## Out[10]: [1, 2, 5, 9]

20.zip()

You can take the iteratable object as a parameter, package the corresponding elements in the object into tuples, and then return the list composed of these tuples.

list1 = [1,2,3]
list2 = ['a','b','c']
list(zip(list1,list2))  ## Package as tuple
## Out[1]:[(1, 'a'), (2, 'b'), (3, 'c')]

list3 = [(1, 'a'), (2, 'b'), (3, 'c')]
list(zip(*list3))  ## Returns a two-dimensional matrix
## Out[2]:[(1, 2, 3), ('a', 'b', 'c')]

21.__ import __()

__ import __ The () function is used to dynamically load classes and functions. If a module changes frequently, it can be used__ import __ () to load dynamically.

a.py file code:
import os  
print ('stay a.py In the file %s' % id(os))
test.py file code:
import sys  
__import__('a')        # Import a.py module
## Out[1]: 4394716136 in a.py file

22.list()

Used to convert tuples to lists.

num_tup = (2,1,9,5)
list(num_tup)
## Out[1]:[2, 1, 9, 5]

23.int()

Used to convert a string or number to an integer.

int('12')  ## Convert string to integer
## Out[1]:12

int(12.222)  ## Converts a number to an integer
## Out[2]:12

24.bytearray()

Returns a new byte array. The elements in this array are variable, and the value range of each element is 0 < = x < 256. That is, bytearray() is a modifiable binary byte format.

exp = bytearray("abcd",encoding="utf-8")
exp[0]  ## Return the ascii code corresponding to "a" of "abcd"
## Out[1]: 97

exp[0] = 99  ## Change the first byte of the string to 99
exp
## Out[2]: bytearray(b'cbcd')

25.dict()

Used to create a dictionary.

dict(zip(['one', 'two', 'three'], [1, 2, 3]))   # The dictionary is constructed by mapping function
## Out[1]: {'one': 1, 'two': 2, 'three': 3}

dict([('one', 1), ('two', 2), ('three', 3)])    # The dictionary can be constructed iteratively
## Out[2]: {'one': 1, 'two': 2, 'three': 3}

26.enumerate()

enumerate(sequence, [start=0]): combine a traversable data object (such as list, tuple or string) into an index sequence, and list data and data subscripts at the same time.

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
list(enumerate(seasons))
## Out[1]: [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

list(enumerate(seasons, start=1))       # Subscript starts with 1
## Out[2]: [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

27.format()

format() is a function to format a string. The basic syntax is to replace the previous% by {} and:.
format() function

print("Site name:{name}, address {url}".format(name="Rookie tutorial", url="www.runoob.com"))
## Out[1]: Website Name: rookie tutorial, address: www.runoob.com

# Setting parameters through dictionary
site = {"name": "Rookie tutorial", "url": "www.runoob.com"}
print("Site name:{name}, address {url}".format(**site))
## Out[2]: Website Name: rookie tutorial, address: www.runoob.com
 
# Set parameters through list index
my_list = ['Rookie tutorial', 'www.runoob.com']
print("Site name:{0[0]}, address {0[1]}".format(my_list))  # '0' is required
## Out[3]: Website Name: rookie tutorial, address: www.runoob.com

28.float()

float(): converts integers and strings to floating point numbers.

float(22)
## Out[1]: 55.0

29.repr()

repr(): converts an object to a form that can be read by the interpreter. Returns the string format of an object.

repr([1,2,3,4])
## Out[1]: '[1, 2, 3, 4]'

30.reversed()

reverse(): reverses the elements in the list.

exp = [1,2,3,4]
exp.reverse()
exp
## Out[1]: [4, 3, 2, 1]

31.frozenset()

frozenset(): returns a frozen collection. After freezing, no elements can be added or deleted from the collection.

frozenset(range(10)) 
## Out[1]: frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})

32.set()

set(): create an unordered non repeating element set, which can be used for relationship testing, delete duplicate data, and calculate intersection, difference, union, etc.
set() function

set([1,1,2,3,4,5])
## Out[1]: {1, 2, 3, 4, 5}

33.str()

str(): returns the string format of an object.

str([1,1,2,3,4,5])
## Out[1]: '[1, 1, 2, 3, 4, 5]'

34.tuple()

tuple(): converts the list to tuples.
tuple() function

tuple([1,2,3,4])
## Out[1]: (1, 2, 3, 4)

tuple({1:2,3:4})    #For the dictionary, a tuple consisting of the key of the dictionary will be returned
## Out[1]: (1, 3)

35.all()

all(iterable): judge whether all elements in the given iteratable parameter iterable (tuple or list) are true. If so, return true; otherwise, return False.
Note: all elements are True except 0, empty, None and False; the return value of empty tuple and empty list is True.

all([0,1,2,3])  ## 1. Element 0 exists
## Out[1]: False

all(['','a','b','c'])  ## 2. Empty element exists
## Out[2]: False

all([None,'a','b','c'])  ## 3. Element None exists
## Out[3]: False

all([False,'a','b','c'])  ## 4. Element False exists
## Out[4]: False

all(['a','b','c'])  ## 5. The above elements do not exist
## Out[5]: True

all([])  ## 6. Empty list
## Out[6]: True

all(())  ## 7. Empty tuple
## Out[7]: True

36.any()

any(): judge whether the given iteratable parameters iterable are all false, then return false. If one of them is true, then return true. If they are all empty, 0, false, then return false. If they are not all empty, 0, false, then return true.

any(["",0,False,None])  ## 1. When all elements are empty, 0, False, None
## Out[1]: False

any(["",0,False,None,1])  ## 2. When there is a non empty, 0, False, None
## Out[2]: True

any([])  ## 3. Empty list
## Out[3]: False

any(())  ## 4. Empty tuple
## Out[4]: Fasle

37.bool()

bool(): converts the given parameter to a boolean type. If there is no parameter, it returns False. 0 is False, non-zero is true.

bool(0)
## Out[1]: Fasle

bool()
## Out[2]: Fasle

bool(1)
## Out[3]: True

38.calllable()

Callable(): check whether an object is callable. If True is returned, the object call may still fail; but if False is returned, the object call will never succeed. Python 3.0 can no longer be used, and the expression hasattr (func, call) needs to be used instead.

callable(0)
## Out[1]: Fasle

def add(a, b):
    return a + b
callable(add)
## Out[2]: True

39.hasattr()

hasattr(): judge whether the object contains corresponding attributes.

class Coordinate:
    x = 10
    y = -5
    z = 0

point1 = Coordinate() 
hasattr(point1, 'x')
## Out[1]: True

hasattr(point1, 'y')
## Out[2]: True

hasattr(point1, 'no')  ## There is no such attribute
## Out[3]: Fasle

40.isinstance()

isinstance(object, classinfo): judge whether an object is a known type, similar to type(). Returns True if the type of the object is the same as the type of parameter 2 (classinfo); otherwise, returns False.
The basic types of classinfo are: int, float, bool, complex, str (string), list, dict (Dictionary), set, tuple

a = 2
isinstance(a,int)
## Out[1]: True

isinstance (a,(str,int,list))  ## Is one of the tuples that returns True
## Out[2]: True

The difference between type and isinstance

type() does not consider a subclass as a parent type and does not consider inheritance. isinstance() will consider the subclass as a parent type and consider the inheritance relationship.

class A:
    pass

## B inherits A
class B(A):
    pass

isinstance(A(), A)
## Out[3]: True
type(A()) == A
## Out[4]: True

isinstance(B(), A) 
## Out[5]: True
type(B()) == A
## Out[6]: False

41.issubclass()

issubclass(class,classinfo): judge whether the parameter class is a subclass of the type parameter classinfo. If class is a subclass of classinfo, return True; otherwise, return False.

class A:
    pass
class B(A):
    pass

issubclass(B,A)
## Out[1]: True

42.dir()

dir(): returns the list of variables, methods and defined types in the current range without parameters; With parameters, the list of properties and methods of the parameters is returned. If the parameter contains a method__ dir__ (), the method will be called. If the parameter does not contain__ dir__ (), this method will collect parameter information to the greatest extent.

43.globals()

globals(): returns all global variables of the current location in dictionary type.

44.help()

help(): used to view a detailed description of the purpose of a function or module.

help(str)

45.id()

id(): used to obtain the memory address of the object.

46.type()

type(name, bases, dict): (class name, tuple of base class, namespace variable defined in dictionary class) one parameter returns the object type, and three parameters return the new type object.

type(1)
## Out[1]: int

class X(object):
    a = 1
type('X', (object,), dict(a=1))  ## Generates a new type X
## Out[2]: __main__.X

47.bin()

bin(): returns the binary representation of an integer int or long int.

bin(8)
## Out[1]: '0b1000'

48.oct()

oct(): converts an integer to an octal string.

oct(8)
## Out[1]: '0o10'

49.hex()

hex(): converts a decimal integer to hexadecimal, expressed as a string.

hex(18)
## Out[1]: ''0x12''

50.hash()

hash(): get the hash value of an object (string or numeric value, etc.).

hash(1)
## Out[1]: 1

51.chr()

chr(): use an integer in the range (256) (i.e. 0 ~ 255) as a parameter to return a corresponding character. The return value is the ASCII character corresponding to the current integer.

chr(0x61)   ## Hex, decimal 97
## Out[1]: a

52.ord()

ord(): it is a pairing function of chr() function (for 8-bit ascii string) or unichr() function (for Unicode object). It takes a character (string with length of 1) as a parameter and returns the corresponding ASCII value or Unicode value. If the given Unicode character exceeds the scope of your Python definition, a TypeError exception will be thrown.

ord('a')
## Out[1]: 97

Posted by rayk on Fri, 17 Sep 2021 09:33:20 -0700