Fundamentals 14 min read

Comprehensive Overview of Python Built‑in Functions, Modules, and Advanced Concepts

This article presents a concise yet thorough guide to essential Python built‑in functions such as map, filter, reduce, sorted, enumerate, zip, any/all, as well as advanced features including lambda expressions, comprehensions, itertools, context managers, partial functions, garbage collection, asyncio, decorators, generators, metaclasses, pathlib, type annotations, and enumerations, each illustrated with clear code examples.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Comprehensive Overview of Python Built‑in Functions, Modules, and Advanced Concepts

map(func, iterable[, iterable, ...]) applies a function to each element of an iterable (or to elements from multiple iterables at the same position) and returns an iterator.

numbers = [1, 2, 3, 4]
squared = map(lambda x: x**2, numbers)
print(list(squared))
# 输出:[1, 4, 9, 16]

filter(func, iterable) constructs an iterator that yields only those elements of an iterable for which the function returns True.

numbers = [1, -2, 3, -4, 5]
positive_numbers = filter(lambda x: x > 0, numbers)
print(list(positive_numbers))
# 输出:[1, 3, 5]

reduce(func, iterable[, initializer]) cumulatively applies a function to the items of an iterable, reducing it to a single value; it resides in the functools module.

from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product)
# 输出:24

sorted(iterable[, key][, reverse]) returns a new list containing all items from the iterable in sorted order; key specifies a custom sort key and reverse=True sorts descending.

words = ['banana', 'apple', 'cherry']
sorted_words = sorted(words, key=len)
print(sorted_words)  # 输出:['apple', 'cherry', 'banana']

enumerate(iterable[, start=0]) yields pairs of index and value, useful for tracking positions in loops.

fruits = ['apple', 'banana', 'mango']
for i, fruit in enumerate(fruits):
print(f"Index: {i}, Fruit: {fruit}")

zip(iterables) aggregates elements from each iterable into tuples, stopping when the shortest iterable is exhausted.

names = ['Alice', 'Bob', 'Charlie']
ages = [24, 30, 19]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")

any(iterable) / all(iterable) return True if any element is truthy or if all elements are truthy, respectively.

numbers = [0, False, None, [], {}, 1]
print(any(numbers))
# 输出:True,因为有1这个真值
print(all(numbers))
# 输出:False,因为有假值存在

lambda creates small anonymous functions; syntax is lambda arguments: expression .

double = lambda x: x * 2
print(double(5))
# 输出:10

list/dictionary/set comprehensions provide concise syntax for constructing collections with optional filtering.

numbers = [1, 2, 3, 4, 5]
even_squares = [x**2 for x in numbers if x % 2 == 0]
print(even_squares)
# 输出:[4, 16]

itertools module offers efficient iterator building blocks such as chain , combinations , etc.

from itertools import chain, combinations
# 合并多个列表
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list(chain(list1, list2))
print(combined)  # 输出:[1, 2, 3, 4, 5, 6]
# 计算组合
combos = list(combinations('ABCD', 2))
print(combos)  # 输出:[('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]

contextlib.contextmanager decorator simplifies creation of context managers for use with the with statement.

from contextlib import contextmanager
@contextmanager
def managed_file(name):
try:
f = open(name, 'r')
yield f
finally:
f.close()
with managed_file('hello.txt') as f:
for line in f:
print(line, end='')

functools.partial fixes some arguments of a function, producing a new callable with fewer required parameters.

from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
print(square(3))
# 输出:9

gc.collect() manually triggers Python's garbage collector, useful in memory‑intensive scenarios.

import gc
# 大量分配和释放内存后...
gc.collect()
# 手动触发垃圾回收

asyncio module and asynchronous programming enable concurrent code using coroutines, event loops, and non‑blocking I/O.

import asyncio
async def my_coroutine():
print("Starting the coroutine")
await asyncio.sleep(1)
# 异步等待1秒
print("Coroutine finished")
asyncio.run(my_coroutine())
# 使用asyncio.run启动事件循环并运行协程

decorator functions modify the behavior of other functions without changing their source code.

def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()

generator functions use yield to produce values lazily, ideal for large data streams.

def fibonacci(n):
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b
for number in fibonacci(100):
print(number, end=' ')

with statement and context manager automatically manage resources such as files.

with open('file.txt', 'r') as file:
content = file.read()

metaclasses allow customization of class creation, enabling dynamic class modifications.

class Meta(type):
def __new__(cls, name, bases, dct):
print(f"Creating class: {name}")
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=Meta):
pass

pathlib module provides an object‑oriented interface for filesystem paths.

from pathlib import Path
path = Path('mydir') / 'myfile.txt'
if not path.exists():
path.write_text("Hello, World!")
content = path.read_text()
print(content)

type annotations (PEP 484) let developers declare expected data types for variables, function parameters, and return values.

def add_numbers(a: int, b: int) -> int:
return a + b
result = add_numbers(1, '2')
# 这将在某些IDE中引发类型警告

Enum class defines a set of named constant values that are unique and comparable.

from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
favorite_color = Color.RED
print(favorite_color.name)
# 输出: RED
PythonIteratorsprogramming fundamentalsdecoratorsModulesasynciobuilt-in-functions
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.