2
import numpy as np
a = np.array([1,2,3])

I know that a[3] will get IndexError Exception. Is there any way to implement such as a[3] = 'new_value' by some magic method such as __call__ or other magic methods which may return the custom value or custom data struct. Or how python implement the list object, and what will happen when access or call the index number of a list.

I'm not very familiar with numpy.

MattDMo
  • 100,794
  • 21
  • 241
  • 231
  • First off, a [Numpy array](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html) is **not** a list, or a subclass of `list`, so please don't confuse the two. I'm not marking this question as an exact duplicate (yet), but please read https://stackoverflow.com/questions/13215525/how-to-extend-an-array-in-place-in-numpy. – MattDMo Apr 04 '23 at 18:25
  • 1
    Is there a particular reason you want to have this implementation with a `numpy` array? Depending on what you want to do, a python [`dictionary`](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) has the functionality that you described. However, I'm not sure what your goal is and if this is appropriate for your needs. – Marcelo Paco Apr 04 '23 at 18:26
  • `a[x]=v` is implemented as a `a.__setitem__(x, v)` call, where `__setitem__` (and `__getitem__`) is defined for the particular class. While `dict` allows you to define a new key this way, `list` does not; you have to use `alist.append(v)` to add an item. `ndarray` also does not allow growth like this either (not like MATLAB). `np.put` and `np.take` have options for handling out-of-bounds indices. – hpaulj Apr 04 '23 at 18:40
  • A user defined class can have its own custom get/set methods, but you can't change the methods of builtin classes. – hpaulj Apr 04 '23 at 19:27
  • Are you more familiar with some other programming language that does what you want? MATLAB comes to mind; for some arrays `javascript` does as well. – hpaulj Apr 04 '23 at 23:15
  • Clear x/y problem. You're asking how to get x, when you shouldn't be attempting to get x at all. You need to back up about ten steps and show more about what you're actually working on. – Reinderien Apr 05 '23 at 00:45
  • Thanks for replying, I am noob for asking question. Now I will try the other way, thanks again :D – winterlover Apr 05 '23 at 11:32

0 Answers0