2

I often find I have something like this:

cur = [0, 0] # the indices into array
matrix = [[1,1,1]]

where I do

matrix[cur[0]][cur[1]]

Is there any sort of unpacking syntax here? Like:

matrix[*cur]
user129393192
  • 797
  • 1
  • 8
  • 1
    No, there clearly can't be (because Python objects can be "indexed" with any object - after all, that's exactly how dictionaries work). If you repeat the logic, wrap it in a function or something. – Karl Knechtel Aug 26 '23 at 01:28
  • Related: [Access nested dictionary items via a list of keys?](/q/14692690/4518341) The top answer's "get" function even happens to work for this case. – wjandrea Aug 26 '23 at 01:37
  • @Karl Why did you close it? That's about dicts, not lists. – wjandrea Aug 26 '23 at 01:44
  • Because, as you said, it's answered there - and all the same principles and reasoning apply. Would you have the same objection if the target were about tuples? – Karl Knechtel Aug 26 '23 at 01:48
  • @Karl Now that I think about it, the main difference is OP's specifically asking about syntax. I've posted an answer specific to that, which wouldn't apply to dicts. (Though maybe `xarray` would work? I haven't used it very much myself. Anyway, I digress.) The other thing is that setting a new value in a dict is different from a list and the syntax OP's showing here also works on the LHS of an assignment, but maybe that's beside the point. Lastly, dicts also support `.get`, which lists don't. – wjandrea Aug 26 '23 at 02:07
  • You just need to pass a tuple – juanpa.arrivillaga Aug 26 '23 at 04:12
  • What do you mean @juanpa.arrivillaga ? I get `TypeError: list indices must be integers or slices, not tuple` – user129393192 Aug 26 '23 at 07:10

1 Answers1

5

If you switch to NumPy and you're using Python 3.11+, then yes, that works.

import numpy as np

cur = [0, 0]
matrix = np.array([[1, 2, 3]])

print(matrix[*cur])  # -> 1

Before Python 3.11, you can just convert to tuple:

print(matrix[tuple(cur)])  # -> 1

Based on the name matrix, NumPy might be a better solution in other ways too. For example you get elementwise operations.


Note: The Python 3.11 syntax change doesn't seem to be documented in the normal places (what's new and grammar). From a quick look, I only found it mentioned under typing.Unpack: "* couldn’t be used in certain places". It is covered in PEP 646 though, which introduced typing.TypeVarTuple.

wjandrea
  • 28,235
  • 9
  • 60
  • 81