Saturday 28 November 2020

Tuple unpacking while indexing

This works:

x = ['foo', 'bar']
y = [*x]
print(y)  # prints ['foo', 'bar']

but this doesn't:

x = ['foo', 'bar']
y[*x]  # raises SyntaxError (not NameError!)

How can I unpack tuples while indexing?

Here are two examples where I'd like to use this approach, but I'm more interested in understanding why *-unpacking seems not to be supported in indexing in general.

import numpy as np

def lookup(a: np.ndarray, coordinates: tuple) -> float:
    return a[*coordinates]

a1 = np.zeros((2, 2))
print(lookup(a1, (0, 1))  # Should print 0

a2 = np.zeros(2, 2, 2))
print(lookup(a2, (0, 0, 1))  # Should print 0

or

from typing import Tuple

NUM_DIMENSIONS = 2  # Might change at a later point in time

# Should be equivalent to Tuple[float ,float]
Result = Tuple[*([float] * NUM_DIMENSIONS)]

def get() -> Result:
    ...


from Tuple unpacking while indexing

No comments:

Post a Comment