Python Standard Library Functions
The Python standard library provides numerous built-in modules. Below is an overview of commonly used functions from the math module.
| Mathematical Symbol | Python Function/Constant | Description |
|---|---|---|
| $\ln x$ | math.log(x) |
Natural logarithm (base e). Standard method for computing natural log. |
| $e^x$ | math.exp(x) |
Computes e raised to the power of x. For example: math.exp(3) calculates $e^3$. |
| $\pi$ | math.pi |
Constant value representing the mathematical constant pi. |
| $\log_b x$ | math.log(x, b) |
Computes logarithm with arbitrary base b. |
1. Anonymous Functions (Lambda)
Definition: Created using the lambda keyword with a concise structure (single-line expression).
Characteristics: No name (anonymous), returns the value of a single expression, implicit return (no return keyword needed).
Common Uses: Typically passed as arguments to higher-order functions (such as map, filter, sorted's key parameter) for simple, one-time logic operations.
from math import *
g = lambda x: (pi * 2) / (1 + log(x))
limit = int(input("Enter limit:"))
result = exp(1.5)
for counter in range(1, limit + 1):
result += g(counter)
print('Result: {:.4f}'.format(result))
This example calculates a sum where each term is $\frac{2\pi}{1+\ln n}$.
2. Regular Functions (def)
Definition: Created using the def keyword.
Characteristics: Must have a name, can contain multiple statements (loops, conditionals, etc.), uses return for explicit value return.
Common Uses: Suitable for complex logic requiring multiple steps or clear code structure.
def calculate_total(price, tax_rate=0.1):
tax = price * tax_rate
total = price + tax
return total
3. Advanced Operations
Chaining Operations with map and filter
This pattern is commonly used for data cleaning and transformation. Lambda functions serve as "plugs" that define data processing rules.
numbers = [4, 12, -3, 7, 15, 0, -1, 22]
positive_values = list(filter(lambda num: num > 0, numbers))
Important: filter returns an iterator, which must be converted to a list using list(). The list() function is a consumer—it continuously requests the next element from the iterator until exhausted. Each retrieved element gets appended to a new list being constructed.
Deep Dive
The Internal Mechanism of Iterators
When filter executes, it creates an iterator object that doesn't carry "the entire dataset." Instead, it stores two key pieces of information: a reference to the original data source and a reference to the predicate logic (the lambda function). It doesn't compute and store intermediate results immediately.
Multi-Level Tuple Sorting
Understanding sorted():
sorted() is a Python built-in function that sorts any iterable (list, tuple, set, etc.) and always returns a new list.
# Verify the return type
print(type(sorted_values))
# Output: <class>
</class>
Example Data Structure:
# Data format: (Name, Age, Score)
employees = [
('Emma', 28, 88),
('Frank', 34, 88),
('Grace', 28, 92),
('Henry', 34, 95)
]
# Sorting requirements:
# 1. Primary: Sort by score in descending order (highest first) **Element 2**
# 2. Secondary: Sort by age in ascending order (when scores tie, younger first) **Element 1**
# (Element 0 is not used for sorting)
# Using lambda to define the sort key
# Tuple (-score, age): negative sign on first element achieves descending order
sorted_employees = sorted(
employees,
key=lambda emp: (-emp[2], emp[1])
)
print("\n--- Multi-level sort (score descending, age ascending) ---")
for person in sorted_employees:
print(person)
# Output:
# ('Henry', 34, 95) # Highest score
# ('Grace', 28, 92) # Second highest
# ('Emma', 28, 88) # Among 88s, younger
# ('Frank', 34, 88) # Among 88s, older
Important Note:
sorted() returns a list after sorting. While the result is a list, the element types remain unchanged. sorted() only rearranges the existing tuples—it doesn't modify their internal structure.
Therefore:
- sorted_employees is a list
- Each item in sorted_employees (such as ('Henry', 34, 95)) is a tuple