Ask Your Question

Revision history [back]

One solution is to define an exchange function as below.

The function starts by checking the validity of the indices.

If called with invalid indices, it will raise a value error.

def exchange(A, B, i, j):
    r"""
    Exchange entry ``i`` of ``A`` and entry ``j`` of ``B``.
    """
    if i not in range(len(A)):
        a = len(A)
        s = f"expected 0 <= i < len(A), got i = {i}, len(A) = {a}"
        raise ValueError(s)
    if j not in range(len(B)):
        b = len(B)
        s = f"expected 0 <= j < len(B), got j = {j}, len(B) = {b}"
        raise ValueError(s)
    A[i], B[j] = B[j], A[i]

To illustrate usage, define two vectors:

sage: A = vector(var('x', n=3, latex_name='x'))
sage: B = vector(var('y', n=4, latex_name='ϵ'))

and exchange some entries:

sage: exchange(A, B, 1, 2)
sage: A
(x0, y2, x2)
sage: B
(y0, y1, x1, y3)

Calling with invalid indices raises an error:

sage: exchange(A, B, 3, 3)
Traceback (most recent call last)
...
ValueError: expected 0 <= i < len(A), got i = 3, len(A) = 3