$ lst = ['a', 'b', 'c', 'd', 'e']
$ lst[[0,3]]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not list
Python list does not support indexing with integer list. R supports it. I am from R. So I thought, why not make it possible?
So here's my code.
class list2(list):
def __getitem__(self, x):
if isinstance(x, __builtins__.list):
#print(x)
return [__builtins__.list.__getitem__(self, y) for y in x]
else:
return __builtins__.list.__getitem__(self,x)
l = list2(['a', 'b', 'c', 'd', 'e'])
l[[2,3]]
It works as I expected.
My question is "can any side effect occur so that I need to take caution in using my list2()
?"
I don't think there is since python list does not allow list in lst[]
or .__getitem__()
in the first place but who knows?
UPDATES
I found one case that does not extend smoothly.
del lst[1]
or del lst[::2]
works fine but
del lst[[1,3]]
does not work.
But I don't think this is a serious problem because it does not break compatibility of existing source.