Lesson 2 of 18
Vector Operations
Vector Operations
We can add vectors, subtract them, and scale them — all element-wise.
a = [1, 2, 3]
b = [4, 5, 6]
add = [a[i] + b[i] for i in range(len(a))] # [5, 7, 9]
sub = [b[i] - a[i] for i in range(len(a))] # [3, 3, 3]
scale = [2 * x for x in a] # [2, 4, 6]
Linear Combination
The most fundamental vector operation is a linear combination:
c = alpha cdot mathbf{a} + eta cdot mathbf{b}
Every vector in the span of and can be expressed this way.
alpha, beta = 2, 3
c = [alpha * a[i] + beta * b[i] for i in range(len(a))]
# 2·[1,2,3] + 3·[4,5,6] = [2,4,6] + [12,15,18] = [14,19,24]
Scalar Multiplication
Multiplying a vector by a scalar scales every component. It stretches or shrinks the vector without changing its direction (unless the scalar is negative — then it flips).
Your Task
Implement linear_combination(a, b, alpha, beta) that returns as a list.
Pyodide loading...
Loading...
Click "Run" to execute your code.