Skip to content
Advertisement

making list index possible for python class list

Python has no function for list index argument in __getitem()__, __setitem()__, __delitem()__. Since I have been an R user for long time, it looks quite natural to utilize list index. I know there is pandas or numpy but it is cumbersome to change the type. AND IT NEEDS IMPORTING EXTRA PACKAGE!

JavaScript

Here is my proposal.

JavaScript

It seems to work okay.

JavaScript

But is there any pitfall? or is there any part that needs to be improved?

Advertisement

Answer

The main pitfall with something like this is that it’s ‘astonishing’, which is generally frowned upon in Python – we expect the default list to behave like the default list.

Aside from that, your implementation mostly looks complete to me. There are maybe a couple of issues:

  • What happens if we use __setitem__ or __delitem__ and list the same index more than once?
  • What happens if we give __setitem__ lists with mismatched lengths?

There’s one key thing that I think it would be worth changing: get rid of lists of indexes, and use tuples instead.

If you pass a comma separated list of indices to __getitem__, these are actually parsed as a tuple!

JavaScript

So, rather than using lists, expect tuples and ditch the double brackets.

In terms of other improvements, it’s probably better to get rid of the references to __builtins__, and use super() to access the functions from the default list implementation, and it’s a good idea to add a custom __repr__ so we don’t mix this up with the default list.

If you add all of these suggestions, it would look something like this (typing added for clarity):

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement