Python Slice Questions
1. why does
a[:]
call a.__getitem__ with an argument:
slice(0, 2147483647, None)
instead of
slice(None, None, None)
2. where are slice lists, like:
a[1,2,3]
documented? The only place I've found is the language reference but the semantics are not explained there. Does this feature exist purely for Numeric Python?
UPDATE: slice lists have existed since 1.4 it appears.
Comments (6)
Michael Hudson on Aug. 17, 2005:
For the former, just make 'a' an instance of a new-style class and be happy.
eleusis on Aug. 19, 2005:
I think I'm missing something here, but how do you get slice lists, and what do you do with them?
>>> a = list()
>>> for i in range(10):
... a.append(i)
...
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[1,2,3]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: list indices must be integers
James Tauber on Aug. 20, 2005:
Eleusis, you've actually hit on one of my points.
If you write a class:
class A:
def __getitem__(self, args):
print args
Then do:
>>> a = A()
>>> a[1,2,3]
(1,2,3)
In other words, the *syntax* supports a[1,2,3] but nothing built-in in Python seems to use it.
Heimy on Aug. 26, 2005:
Of course the syntax supports a[1,2,3], because there is no special syntax involved at all. That's the same as if you write a[(1,2,3)], and that's an only argument, not three. Then you have to look at the semantics. It works for dictionaries:
>>> a = { (1,2,3): 4 }
>>> a[1,2,3]
4
But with sequences you get an exception, as for them, only integer indexes make sense (if you're not slicing). So, no special syntax here.
gideon on Aug. 24, 2007:
I realize this is quite an old post. It's just that I found this in google and am looking into this myself. It's a comment for posterity.
The syntax specification which can be found at
http://docs.python.org/ref/slicings.html#tok-slicing
shows that there's actually special syntax allowing slicing lists. In other words, it's not just a tuple.
The syntax allows us to write
a[1:4, 5, 3:2]
which doesn't have any clear meaning to me and doesn't seem to work either.
As to why it is allowed, is a mystery to me.
Last Modified: Aug. 17, 2005
Author: James Tauber
Calvin Spealman on Aug. 17, 2005:
Because that way there is not a special case for the slicing, and the tuple is just passed as the key. that is, the tuple expession takes precedence over the [] operator. Both cases seem to stem from reduction of special cases which are Very Bad Things.