Comprehensive Guide to Python Built-in Functions with Examples
This article provides a detailed overview of Python's 68 built-in functions, categorizing them into numeric operations, data structures, scope handling, iterators, and code execution, and includes clear code snippets and explanations to help beginners master fundamental Python capabilities.
Python Built-in Functions Overview
Python provides a set of built‑in functions that can be used directly without importing any modules, such as print() and input() . Up to version 3.6.2, there are 68 built‑in functions, which are listed below.
<code>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()
</code>Numeric Related Functions
1. Data Types
bool – Boolean type (True, False)
int – Integer type
float – Floating‑point type
complex – Complex number type
2. Base Conversions
bin() – Convert to binary
oct() – Convert to octal
hex() – Convert to hexadecimal
<code>print(bin(10)) # 二进制:0b1010
print(hex(10)) # 十六进制:0xa
print(oct(10)) # 八进制:0o12
</code>3. Mathematical Operations
abs() – Absolute value
divmod() – Quotient and remainder
round() – Round to nearest
pow(a, b[, mod]) – Power (optional modulo)
sum() – Sum of iterable
min() – Minimum value
max() – Maximum value
<code>print(abs(-2)) # 2
print(divmod(20, 3)) # (6, 2)
print(round(4.51)) # 5
print(pow(10, 2, 3)) # 1
print(sum([1,2,3,4,5,6,7,8,9,10])) # 55
print(min(5,3,9,12,7,2)) # 2
print(max(7,3,15,9,4,13)) # 15
</code>Data Structure Related Functions
1. Sequences
(1) Lists and tuples
list() – Convert an iterable to a list
tuple() – Convert an iterable to a tuple
<code>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)
</code>(2) Related functions
reversed() – Return an iterator that yields items in reverse order
slice() – Create a slice object for list slicing
<code>lst = "你好啊"
it = reversed(lst)
print(list(it)) # ['啊', '好', '你']
lst = [1,2,3,4,5,6,7]
print(lst[1:3]) # [2, 3]
s = slice(1,3,1)
print(lst[s]) # [2, 3]
</code>2. Collections
dict() – Create a dictionary
set() – Create a set
frozenset() – Create an immutable set
3. Collection Helpers
len() – Number of items
sorted() – Return a new sorted list
enumerate() – Enumerate items with indices
all() – True if all items are true
any() – True if any item is true
zip() – Aggregate elements from multiple iterables
filter() – Filter items using a predicate
map() – Apply a function to each item
<code># sorted example
lst = [5,7,6,12,1,13,9,18,5]
lst.sort()
print(lst) # [1, 5, 5, 6, 7, 9, 12, 13, 18]
print(sorted(lst, reverse=True)) # [18, 13, 12, 9, 7, 6, 5, 5, 1]
# enumerate example
for index, el in enumerate(['one','two','three'], 1):
print(index, el)
# filter example
def is_odd(i):
return i % 2 == 1
print(list(filter(is_odd, range(1,10)))) # [1, 3, 5, 7, 9]
# map example
print(list(map(lambda x: x*2, [1,2,3]))) # [2, 4, 6]
</code>Scope Related Functions
locals() – Return a dictionary of the current local symbol table
globals() – Return a dictionary of the current global symbol table
<code>def func():
a = 10
print(locals()) # {'a': 10}
print(globals()) # {...}
func()
</code>Iterator & Generator Functions
range() – Generate a sequence of numbers
next() – Retrieve the next item from an iterator
iter() – Get an iterator from an iterable
<code>for i in range(15, -1, -5):
print(i) # 15 10 5 0
lst = [1,2,3,4,5]
it = iter(lst)
print(next(it)) # 1
print(it.__next__()) # 2
</code>String Execution Functions
eval() – Evaluate a string as an expression and return the result
exec() – Execute a string as Python code (no return value)
compile() – Compile source code into a code object
<code>s1 = input("请输入 a+b:") # e.g., 8+9
print(eval(s1)) # 17
s2 = "for i in range(5): print(i)"
exec(s2) # prints 0‑4
code = "for i in range(3): print(i)"
com = compile(code, "", mode="exec")
exec(com) # 0 1 2
</code>Input/Output Functions
print() – Output to console
input() – Read user input
<code>print("hello", "world", sep="*", end="@") # hello*world@
</code>Memory‑Related Functions
hash() – Return the hash value of an object
id() – Return the memory address of an object
<code>s = "alex"
print(hash(s)) # e.g., -168324845050430382
print(id(s)) # e.g., 2278345368944
</code>File Operations
open() – Open a file and return a file object
<code>f = open('file', mode='r', encoding='utf-8')
content = f.read()
f.close()
</code>Module Handling
__import__() – Dynamically import a module by name
<code>name = input("请输入你要导入的模块:")
__import__(name)
</code>Utility Functions
help() – Show the help page for an object
callable() – Check if an object appears callable
dir() – List the attributes of an object
<code>print(help(str))
print(callable(10)) # False
print(dir(tuple))
</code>Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.