Python built-in functions

Posted by agravayne on Mon, 17 Jan 2022 19:45:50 +0100

Official documentation of Python built-in functions

1. abs() function

Returns the absolute value of a number

print(abs(-45)) #Return 45
print(abs(-0.5)) #Return 0.5

2. all() function

It is used to judge whether all elements in a given parameter are True. If yes, it returns True; otherwise, it returns False. Elements are True except 0, "", None and False; The return value of empty tuple and empty list is True

print( all( [0.1,1,-1] ) ) # Return True
print( all( (None,1) ) ) # Returns False (one of the elements is None)
print( all( [0,1,-1] ) ) # Returns False (one of the elements is 0)
print( all( [" ","a",""] ) ) # Returns false (the third element is empty)

3. any() function

It is used to judge whether all the given parameters are False. If yes, it returns False. If one of them is True, it returns True. Elements are True except 0, empty and False

# All parameters are not 0, empty or FALSE
print(any("-45")) # True
print(any(["-45"])) # True
print( any( ("0","ab","") ) ) # True (Note: the first parameter 0 is enclosed in double quotation marks and expressed as a string)
# All parameters are 0, empty and False
print( any( (0,"") ) ) # False
print( any( (0,"",False) ) ) # False

4. bin() function

Returns the binary representation of an integer int or long int

print( bin(10) ) # 0b1010
print( bin(133) ) # 0b10000101

5. bool() function

Used to convert the given parameter to boolean type. If the parameter is not empty or 0, it returns True; If the parameter is 0 or has no parameter, False is returned

print( bool(10) ) # True
print( bool([0]) ) # True
print( bool(["123","s",0]) ) # True
print( bool(0) ) # False
print( bool() ) # False

6. bytearray() function

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

b = bytearray("abcd",encoding="utf-8")
print(b[0]) # Return the number 97, that is, print out the ascii code corresponding to "a" of "abcd"
b[0] = 99 # Modify the first byte of the string to 99 (that is, the corresponding letter is "c")
print(b) # Return: bytearray(b'cbcd ') -- the first byte a has been modified to c

7. callable() function

Used to check whether an object is callable. It returns True for functions, methods, lambda functions, classes, and class instances that implement the call method. (anything that can be bracketed can be called)

def sayhi():
    pass# First define a function sayhi()
print(callable(sayhi)) # True
a = 1
print(callable(a))# False

8. chr() function

Use an integer in the range(256) (i.e. 0 ~ 255) as a parameter to return a corresponding ASCII value

# Print out the characters corresponding to the number 98 in ascii code
print(chr(98)) # Return: b

9. dict() function

Used to convert tuples / lists to dictionary format.

print(dict(a='a', b='b', t='t'))
# Return: {B ':'b','a ':'a','t ':'t'}
print(dict( [ ('one',1),('two',2),('three',3) ] ) ) # The dictionary can be constructed iteratively
# Return: {two ': 2,' one ': 1,' three ': 3}
print(dict(zip(["1","2","3"],["a","b","c"]))) # The dictionary is constructed by mapping function
# Return: {'2':'b ',' 3 ':'c', '1':'a '}

10. dir() function

Without parameters, return the list of variables, methods and defined types in the current range; With parameters, the list of properties and methods of the parameters is returned.

print(dir()) # Get the attribute list of the current module
# Return: ['_builtins',' _cached ',' _doc ',' _file ',' _loader ',' _name ',' _package ',' _spec ']
print(dir([])) # How to view a list
return:['__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__', '__sizeof__', '__str__', '__subclasshook__',
'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort']

11. divmod() function

Combine the results of divisor and remainder operations to return a tuple containing quotient and remainder (quotient x, remainder y)

print( divmod(5,2) ) # Return: (2, 1)
print( divmod(5,1) ) # Return: (5, 0)
print( divmod(5,3) ) # Return: (1, 2)

12. enumerate() function

It is used to 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. It is generally used in the for loop. Python 2.3. The above versions are available, and the start parameter is added in 2.6

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

13. eval() function

Used to execute a string expression and return the value of the expression

print(eval('3 * 2')) #6
x = 7
print(eval('3+x')) #10

14. exec() function

Execute Python statements stored in strings or files. exec can execute more complex Python code than eval

exec("print('Hello World')") # Execute a simple string
# Hello World
exec("for i in range(5): print('iter time is %d'%i)") # Execute a complex for loop
iter time is 0
iter time is 1
iter time is 2
iter time is 3
iter time is 4

15. filter() function

It is used to filter the sequence, filter out the unqualified elements, and return an iterator object, which can be converted into a list with list().
Note: filter() receives two parameters, the first is a function and the second is a sequence. Each element of the sequence is passed to the function as a parameter for judgment, and then returns True or False. Finally, the element that returns True is placed in the new list.

res = filter(lambda n:n>5,range(10))#Filter out the data in 0-9 that does not conform to n > 5
for i in res:                       #Cyclic printing of data conforming to n > 5
    print(i)
6
7
8
9

See my other blog for details: Python higher order functions_ map,reduce,sorted and filter

16. format() function

Is a function to format a string. The basic syntax is to replace the previous% by {} and:. The format function can accept unlimited parameters, and the positions can be out of order

# Location mapping
print( "{}{}".format('a','1') )
# a1
print('name:{n},url:{u}'.format(n='alex',u='www.xxxxx.com'))
# name:alex,url:www.xxxxx.com
# Element access
print( "{0[0]},{0[1]}".format(('baidu','com')) ) # In order
# baidu,com
print( "{0[2]},{0[0]},{0[1]}".format(('baidu','com','www')) ) # Out of order
# www,baidu,com

17. float() function

Used to convert integers and strings to floating point numbers

print(float(1))
# 1.0
print(float(0.1))
# 0.1

18. frozenset() function

Returns a frozen collection (an unordered sequence of non repeating elements). After freezing, no elements can be added or deleted from the collection

a = frozenset(range(10)) # Create a frozen collection first
print(a)
# frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
del a[0] # An error was reported attempting to delete an element in frozen set a
# TypeError: 'frozenset' object doesn't support item deletion
b = frozenset("happy") # Converts a string into a collection
print(b)
# frozenset({'a', 'h', 'p', 'y'}) # Unordered and unrepeated
c = frozenset() # Create an empty collection
print(c)
# frozenset() # If no parameters are provided, an empty collection is generated by default

19. globals() function

All global variables of the current location are returned in dictionary format

print(globals()) # The globals function returns a dictionary of global variables, including all imported variables.
{'__file__': 'C:/Users/Administrator/PycharmProjects/test/day4/Built in function globals().py', '__spec__': None, '__doc__': None, '__package__': None, 'a':
'append', '__cached__': None, '__loader__':
<_frozen_importlib_external.SourceFileLoader object at 0x0000000000666B00>,
'__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__'}

20. hasattr() function

Used to determine whether an object contains corresponding attributes. Returns True if the object has this property; otherwise, returns False.

class t:
	a = 1
	b = 2
	c = 3
p = t()
print(hasattr(p,'a')) # True
print(hasattr(p,'b')) # True
print(hasattr(p,'x')) # False

21. hash() function

Used to get the hash value of an object (number or string, etc.). It cannot be directly applied to list, set and dictionary
Note: when hash() is used on an object, the result is related not only to the content of the object, but also to the id() of the object, that is, the memory address.

print(hash(1)) # 1
print(hash(20000)) # 20000
print(hash('123')) # -6436280630278763230
print(hash('ab12')) # 5468785079765213470
print(hash('ab12')) # 5468785079765213470

22. help() function

Use to view a detailed description of the purpose of a function or module

help('sys') # View help for sys module
help('str') # View help for str data types
a = [1,2,3]
help(a) # View list help information
help(a.append) # Displays help for the append method of the list

23. hex function

Used to convert an integer to a hexadecimal number. Returns a string starting with 0x

print(hex(1)) # 0x1
print(hex(-256)) # -0x100
print(type(hex(-256))) #<class 'str'>

24. id() function

Used to get the memory address of the object

a = "123" # character string
print(id(a)) # 13870392
b = [1,2,3] # list
print(id(b)) # 7184328
c = {'num1':1,'num2':2,'num3':3} # Dictionaries
print(id(c)) # 6923656

25. input() function

Accept a standard input data and return it as string type. This function is the most commonly used. In Python 3 Raw in X_ input() and input() are integrated, leaving only the input() function

a = '123456'
b = input("username:")
if b == a : # If the input data of b is equal to the data stored by a, print "right“
	print("right")
else: # Otherwise, print "wrong"“
	print("wrong")

26. int() function

Used to convert a string or number to an integer

print(int())#When no parameter is passed in, the result is 0
print(int(0.5))#Remove the decimal part to get the result 0
print(int(3)) # Get result 3
print(int('0xa',16)) # The hexadecimal number "0xa" is converted to a decimal integer to get the result 10
print(int("00010"),2) # The binary number "00010" is converted to a decimal integer and the result is 2

27. isinstance() function

To determine whether an object is a known type and return a Boolean value. Similar type()

a = 2
print(isinstance(a,int)) # True
print(isinstance(a,str)) # False
print(isinstance(a,(str,tuple,dict))) # False
print(isinstance(a,(str,tuple,int))) # Returns True if it is one of the tuples
  • The difference between isinstance() and type():
    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.
    If you want to judge whether the two types are the same, isinstance() is recommended.
class A:
	pass
class B(A):
	pass
print(isinstance(A(),A)) # True
print( type(A()) == A ) # True
print(isinstance(B(),A)) # True
print( type(B()) == A ) # False --type() does not consider inheritance

28. issubclass() function

It is used to judge whether the parameter class is a subclass of the type parameter classinfo. If yes, it returns True; otherwise, it returns False.
Syntax: issubclass(class,classinfo)

class a:
	pass
class b(a): # b inherits a, that is, b is a subclass of A
	pass
print(issubclass(a,b)) # Judge whether a is a subclass of b?
# False
print(issubclass(b,a)) # Judge whether b is a subclass of a?
# True

29. iter() function

Used to generate iterators. list, tuple, etc. are iteratable objects. We can obtain the iterators of these iteratable objects through the iter() function, and then continuously use the next() function to obtain the next data for the obtained iterators. The iter() function actually calls the iter method of the iteratable object
Note: after the last data has been iterated, calling the next() function again will throw an exception of StopIteration to tell us that all data have been iterated.

it = [1,2,3]
it_list = iter(it)
print(next(it_list))
# 1
print(next(it_list))
# 2
print(next(it_list))
# 3
print(next(it_list))
# StopIteration

30. len() function

Returns the length of an object (character, list, tuple, etc.) or the number of elements

# The len() method returns the length of an object (character, list, tuple, etc.) or the number of elements.
print(len('1234')) # String, return character length 4
print(len(['1234','asd',1])) # List, return the number of elements 3
print(len((1,2,3,4,50))) # Tuple, return the number of elements 5
print(len(12)) # Note: the integer type is not applicable, otherwise an error will be reported
# TypeError: object of type 'int' has no len()

31. list() function

Used to convert tuples to lists
Note: tuples are very similar to lists, except that the element values of tuples cannot be modified. Tuples are placed in brackets and lists are placed in square brackets

print(list((1,2,3))) # [1, 2, 3]

32. map function

Receive function f and list, and get a new list and return it by successively acting function f on each element of the list.

res = map(lambda x : x**2, [1, 2, 3, 4, 5])#Using lambda functions
for i in res:
    print(i)
1
4
9
16
25

See my other blog for details: Python higher order functions_ map,reduce,sorted and filter

33. max() function

Returns the maximum value of a given parameter, which can be a sequence

print("max(10,20,30):" , max(10,20,30) )
# max(10,20,30): 30
print("max(10,-2,3.4):" , max(10,-2,3.4) )
# max(10,-2,3.4): 10
print("max({'b':2,'a':1,'c':0}):" , max({'b':2,'a':1,'c':0}) ) # Dictionary. Press key by default
 sort
# max({'b':2,'a':1,'c':0}): c

34. min() function

Returns the minimum value of a given parameter, which can be a sequence

print("min(10,20,30):" , min(10,20,30) )
# min(10,20,30): 10
print("min(10,-2,3.4):" , min(10,-2,3.4) )
# min(10,-2,3.4): -2
print("min({'b':2,'a':1,'c':0}):" , min({'b':2,'a':1,'c':0}) ) # Dictionary. Press key by default
 sort
# min({'b':2,'a':1,'c':0}): a

35. next() returns the next item of the iterator

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

36. oct() function

Converts an integer to an octal string

print(oct(10)) # 0o12
print(oct(255)) # 0o377
print(oct(-6655)) # -0o14777

37. open() function

It is used to open a file and create a file object, and the related methods can call it for reading and writing

f = open("test1.txt","w",encoding="utf-8") # Create a file
print(f.write("abc"))
f = open("test1.txt","r",encoding="utf-8") # Read file data
print(f.read())

38. ord() function

Is the pairing function of chr(), which 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 defined range, an exception of TypeError will be thrown

# Print the character b (string with length of 1) as the corresponding character in ascii code
print( ord('b') ) # Return: 98
print( ord('%') ) # Return: 37

39. pow() function

Returns the value of x to the power of y
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.

# Call directly through built-in methods
print(pow(2,2)) # Quadratic of 2
# 4
print(pow(2,-2)) # Negative quadratic of 2
# 0.5
print(pow(2,2,3)) #Quadratic remainder of 2
# 1

40. print() function

For printout, the most common function. print in Python 3 X is a function, but in Python 2 The X version is just a keyword

print(abs(-45)) # 45
print("Hello World!") # Hello World!
print([1,2,3]) # [1, 2, 3]

41. range() function

You can create a list of integers, which is generally used in the for loop. Syntax: range(start, stop[, step])

for i in range(10):
	print(i) # Print the numbers 0-9 in sequence
for a in range(0,10,2): # Step size is 2
	print(a) # Print 0,2,4,6,8
for b in range(10, 0, -2): # Step size is - 2
	print(b) # Print 10,8,6,4,2

42. reduce() function

The elements in the parameter sequence are accumulated. In Python 3, reduce() is placed in the functools module. If you want to use it, you need to introduce the functools module first

import functools
a = functools.reduce(lambda x,y:x+y,[1,2,3])
print(a) # 6, i.e. from 1 to 3
b = functools.reduce(lambda x,y:x+y,range(10))
print(b) # 45, i.e. from 0 to 9

43. repr() function

Converts an object to a form that can be read by the interpreter. Returns the string format of an object

r = repr((1,2,3))
print(r) # (1, 2, 3)
print(type(r)) # <class 'str'>
dict = repr({'a':1,'b':2,'c':3})
print(dict) # {'c': 3, 'a': 1, 'b': 2}
print(type(dict)) # <class 'str'>

44. reverse() function

Returns an inverted iterator. reversed(seq) the sequence to be converted, which can be tuple, string, list or range

rev = reversed( [1,2,3,4,5] ) # list
print(list(rev))
# [5, 4, 3, 2, 1]
rev1 = reversed( "school" ) # tuple
print(tuple(rev1))
# ('l', 'o', 'o', 'h', 'c', 's')
rev2 = reversed(range(10)) # range
print(list(rev2))
# [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

45. round() method

Returns the rounded value of a floating-point number x. (unless there is no requirement for accuracy, try to avoid using the round() function)

print( round(4.3)) # When there is only one parameter, it is reserved to an integer by default
# 4
print( round(2.678,2)) # Keep 2 decimal places
# 2.68
print( round(5/3,3)) # Operation expression with 3 decimal places
# 1.667
print(round(12.45,1))#When the last decimal place is an even number, round it down. The last decimal place here is 4, which is an even number
#12.4
print(round(13.5))#When the last decimal place is odd, round it up. The last decimal place here is 3, which is odd
#14

46. set() function

Create an unordered non repeating element set, which can be used for relationship testing, delete duplicate data, and calculate intersection, difference, union, etc

a = set('school')
print(a) # The duplicate is deleted and the result is: {'o', 'C','s', 'l', 'H'}
b = set([1,2,3,4,5])
c = set([2,4,6,8,10])
print(b & c) # Intersection, the result is {2,4}
print(b | c) # Union, the result is {1, 2, 3, 4, 5, 6, 8, 10}
print(b - c) # Difference set, the result is {1, 3, 5}

47. slice() function

Realize the slice object, which is mainly used for parameter transfer in the slice operation function

a = slice("school")
print(a) # slice(None, 'school', None)

48. sorted() function

Sort (default ascending) all iteratable objects

#Sort the list
print(sorted([1,2,5,30,4,22])) # [1, 2, 4, 5, 22, 30]
# Sort Dictionaries
dict = {23:42,1:0,98:46,47:-28}
print( sorted(dict) ) # Sort key s only
# [1, 23, 47, 98]
print( sorted(dict.items()) ) # Sort by key by default
# [(1, 0), (23, 42), (47, -28), (98, 46)]
print( sorted(dict.items(),key=lambda x:x[1]) ) # Sorting by value using anonymous functions
# [(47, -28), (1, 0), (23, 42), (98, 46)]

49. str() function

Convert object to string format

a = str((1,2,3))
print(a) # Print a and get the result (1, 2, 3)
print(type(a)) # Print the type of a and get the result < class' STR '>

50. sum() function

Sum the parameters

print( sum([1,2,3]) ) # 6
print( sum([1,2,3],4) ) # Add 4 after calculating the sum in the list to get the result of 10
print( sum( (1,2,3),4 ) ) # The tuple calculates the sum and adds 4 to get the result 10

51. tuple() function

Converts a list to tuples.
Note: tuples are very similar to lists. The difference is that the element values of tuples cannot be modified. Tuples are placed in brackets and lists are placed in square brackets.

print( tuple([1, 2, 3])) # (1,2,3)

52. type() function

If you only have the first parameter, return the type of the object, and the three parameters return the new type of object

print(type(1)) # <class 'int'>
print(type("123")) # <class 'str'>
print(type([123,456])) # <class 'list'>
print(type( (123,456) ) ) # <class 'tuple'>
print(type({'a':1,'b':2}) ) # <class 'dict'>

53. zip() function

It is used to take the iteratable object as a parameter, package the corresponding elements in the object into tuples, and then return the object composed of these tuples. The advantage of this is to save a lot of memory. You can use the list() transformation to output the list. If the number of elements of each iterator is inconsistent, the length of the returned list is the same as the shortest object. With the * operator, tuples can be decompressed into lists

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9, 10]
for i in zip(a,b):
    print(i)
# Return result:
# (1, 4)
# (2, 5)
# (3, 6)
print(list(zip(a,b))) # list() to list
# [(1, 4), (2, 5), (3, 6)]
print(list(zip(b,c))) # The number of elements is consistent with the shortest list
# [(4, 7), (5, 8), (6, 9)]
a1,a2 = zip(*zip(a,b)) # Unzip with zip(*)
print(list(a1)) # [1, 2, 3]
print(list(a2)) # [4, 5, 6]

Topics: Python Back-end