Built-in Functions
Function list
abs
return the absolute value of a number
#!/usr/bin/python
print(abs(-10))
print(abs(-3.14))
all&any
return True if all elements of the iterable are true
#!/usr/bin/python
l = [not (i % 3) for i in range(1, 5)] # [False, False, True, False]
print(any(l)) # True
print(all(l)) # False
bin
convert an integer number to a binary string prefixed with “0b”
#!/usr/bin/python
print(bin(9)) # convert int to bin
bool
if the argument is false or omitted, this returns False; otherwise it returns True
#!/usr/bin/python
print(bool(0)) # False
print(bool()) # False
print(bool(1)) # True
print(bool(range(4))) # True
chr
Converts a Unicode code point to a character, The valid range for the argument is from 0 through 1,114,111
Raise ValueError, if i is outside that range
#!/usr/bin/python
for i in range(256):
print(chr(i))
dir
without arguments, return the list of names in the current local scope, with an argument, attempt to return a list of valid attributes for that object
#!/usr/bin/python
print(dir())
print(dir(str))
divmod
quotient and remainder
#!/usr/bin/python
a = divmod(10, 3) # same as (a//b, a%b)
print(a) # (3, 1), quotient, remainder
d = divmod(3.5, 3) # (q, a%b)
print(d) # (1.0, 0.5)
enumerate
return an enumerate object instead of a list of tuples
#!/usr/bin/python
for index, ele in enumerate(range(4)):
print(index, ele)
r = enumerate(range(0, 40, 10))
print(list(r))
eval
expression argument is parsed and evaluated as a Python expression
#!/usr/bin/python
x = 1
print(eval('1+x'))
float
return a floating number from a number or string
raise OverflowError, if the argument is outside the range of a Python float
#!/usr/bin/python
print(float("+3.14")) # 3.14
print(float(" -3.14")) # -3.14
print(float("3.14e+2")) # 314.0
print(float("3.14e-2")) # 0.0314
print(float("Inf")) # inf
help
invoke the built-in help system, is intended for interactive use
help() # switch to interactive help environment, Ctrl+C to quit
help(str) # get the help documentation of str class
hex
convert an integer number to a lowercase hexadecimal string prefixed with “0x”
#!/usr/bin/python
print(hex(20)) # convert int to hex
id
return the “identity” of an object, which is not the physical address
#!/usr/bin/python
l = [1, 2, 3, 4]
l2 = l
l3 = [1, 2, 3, 4]
print(id(l), id(l2)) # l and l2 have same ids
print(id(l), id(l3)) # l and l3 have different ids
input
reads a line from input and converts it to a string
#!/usr/bin/python
value = input('Input an integer number: ')
print(int(value)*100)
int
return an integer from a number or string, return 0 if no arguments are given
#!/usr/bin/python
print(int('10')) # string to int
print(int(3.14)) # float to int
print(int(0b1001)) # binary number to int
print(int(0o1001)) # octal number to int
print(int(0xF1)) # hexadecimal to int
iter
Return an iterator object
#!/usr/bin/python
i = iter(range(10))
try:
while True:
print(next(l)) #if no more element, raise StopIteration
except StopIteration:
pass
len
Return the length (the number of items) of an object, argument may be a sequence or a collection
#!/usr/bin/python
print(len(range(4))) # 4
print(len({'Name': 'Lin', 'Age': 39})) # 2
max
return the largest item in an iterable or the largest of two or more arguments
#!/usr/bin/python
m = max([1, 4, 2, 6]) # 6
print(m)
m = max(1, 4, 2, 6) # 6
print(m)
min
return the smallest item in an iterable or the smallest of two or more arguments
#!/usr/bin/python
m = min([1, 4, 2, 6]) # 1
print(m)
m = min(1, 4, 2, 6) # 1
print(m)
next
Retrieve the next item from the iterator
#!/usr/bin/python
l = iter(range(10))
try:
while True:
print(next(l)); #if no more element, raise StopIteration
except StopIteration:
print('Reach to the end ...')
pass
ord
return an integer representing the Unicode code point of that characte
#!/usr/bin/python
print(ord('a'))
print(ord(u'a'))
print(ord(u'\u2020'))
object
Return a new featureless object
Object is a base for all classes
Has the methods that are common to all instances of Python classes
Does not have a __dict__
o = object
print(p.__doc__)
oct
convert an integer number to an octal string prefixed with “0o”
#!/usr/bin/python
print(oct(9)) # convert int to oct
range
return a range, instead of a list
#!/usr/bin/python
r = range(0, 10, 1)
print(type(r)) # range
print(len(r)) # 10
print(list(r)) # convert a range to list, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for e in r:
print(e, end=' ')
print()
pow
return x to the power y
#!/usr/bin/python
print(pow(2, 3)) # 8
print(pow(2, 3, 3)) #2, pow(2, 3) % 3
print
print(value1, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
- values, can take multiple arguments
- sep, default deliminator is a single space
- end, end the line with a character, default character is '\n', which changes to a new line
- file, argument must be an object with a write(string) method, default is sys.stdout
- flush, use buffer or forcibly flushed
#!/usr/bin/python
print('Welcome "Lin" ...') # single quote enclose double quote
print("Welcome 'Lin' ...") # double quote enclose single quote
print("""Welcome "Lin" and 'Yanhua' ...""") # triple quotes enclose single quote and double quote
print('''Welcome "Lin" and 'Yanhua' ...''')
# multiline strings
print("""Welcome to Python,
Lin and
Yanhua""")
#!/usr/bin/python
print("Welcome to Python 3!")
print("Welcome "+"to "+"Python 3!") # use string concatenation
print("Welcome", "to", "Python 3!") # automatically add space between arguments
print("%s %s %s!" % ("Welcome", "to", "Python 3")) # use old format style
print("{} {} {}!".format("Welcome", "to", "Python 3")) # use new format style
#!/usr/bin/python
print(1, 2, 3, 4, sep='|') # 1|2|3|4
print(1, end='|') # end the line with a character
print(2, end='|')
print() # change to a new line
f = open("data.txt","w")
print('Hello World!', file=f) # output to a file
f.close()
repr
str, compute the “informal” string representation of an object
repr, compute the “official” string representation of an object, used for debugging and development
#!/usr/bin/python
import datetime
today = datetime.datetime.now()
# str
s = 'Hello, Geeks.'
print(str(s)) # Hello, Geeksl
print(str(2.0/11.0)) # 0.1818
print(str(today)) # 2019-02-04 23:21:52.332522
# repr
s = 'Hello, Geeks.'
print(repr(s)) # 'Hello, Geeks.'
print(repr(2.0/11.0)) # 0.1818
print(repr(today)) # datetime.datetime(2019, 2, 4, 23, 21, 52, 332522)
reversed
Return a reverse iterator
#!/usr/bin/python
l = [1, 2, 3, 4]
a = reversed(l) # <class 'list_reverseiterator'>
print(list(a)) # [4, 3, 2, 1]
print(list(a)) # [], a has been consumed
b = reversed(range(4)) # <range_iterator object at 0x10583b9f0>
print(list(b)) # [3, 2, 1, 0]
print(list(b)) # [], b has been consumed
round
Return number rounded to ndigits precision after the decimal point
round(3.14) # 3
round(3.1415926, 2) # 3.14
slice
is used to slice a given sequence
#!/usr/bin/python
s = slice(1, 10, 2)
l = range(10)
print(list(l[s])) # [1, 3, 5, 7, 9]
l2 = list(range(10))
print(l2[s]) # [1, 3, 5, 7, 9]
sorted
return a new sorted list from the items in iterable
#!/usr/bin/python
# sort list
l = [1, 5, 3]
l2 = sorted(l) # only sort the objec with the same data type
print(l2) # [1, 3, 5]
# sort tuple
l = (1, 5, 3)
l2 = sorted(l)
print(type(l2)) # list
print(l2)
# sort dict
d = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
d2 = sorted(d) # return a list containing the sorted keys
print(d2) # ['Age', 'Class', 'Name']
str
Return a str version of object
#!/usr/bin/python
print(str(10)) # int to str
print(str(3.14)) # float to str
print('{0:#b}'.format(0b1001)) # binary number to str
sum
returns the total of an iterable
#!/usr/bin/python
a = range(10)
print(sum([1, 2, 3, 4])) # 10
print(sum([1, 2, 3, 4], 1)) # 1 + 2 + 3 + 4 + 1
type
return the type of an object
#!/usr/bin/python
print(type('Hello World!')) # str
vars
Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute
#!/usr/bin/python
class Vehicle(object):
def __init__(self, maker, year):
self.maker = maker
self.year = year
def main():
v = Vehicle('Buick', 1998)
d = vars(v)
print(d) # {'maker': 'Buick', 'year': 1998}
print(vars(Vehicle)) # {'__module__': '__main__', '__init__': <function Vehicle.__init__ at 0x10daee2f0>, '__dict__': <attribute '__dict__' of 'Vehicle' objects>, '__weakref__': <attribute '__weakref__' of 'Vehicle' objects>, '__doc__': None}
if __name__ == '__main__':
main()
zip
Make an iterator that aggregates elements from each of the iterables
#!/usr/bin/python
x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
print(list(zipped)) # [(1, 4), (2, 5), (3, 6)]
Reference