Suggested feature: slice syntax within tuples (or even more generally)?

Ian Kelly ian.g.kelly at gmail.com
Mon Feb 25 05:28:06 EST 2013


On Sun, Feb 24, 2013 at 6:10 PM, Andrew Robinson
<andrew3 at r3dsolutions.com> wrote:
> I've read through the whole of the subject, and the answer is no, although I
> think allowing it in (::) is a *very* good idea, including as a replacement
> for range or xrange.
>
> s=1:2:3
> for i in s:
> for i in (1:2:3) :

Eww, no.  I can appreciate the appeal of this syntax, but the problem
is that ranges and slices are only superficially similar.  For one,
ranges require a stop value; slices do not.  What should Python do
with this:

for i in (:):

Intuitively, it should result in an infinite loop starting at 0.  But
ranges require a stop value for a very good reason -- it should not be
this easy to accidentally create an infinite for loop.  So I would
advocate that this should raise an error instead.  If the user really
wants an unlimited counting loop, let them continue to be explicit
about it by using itertools.count.  On the other hand, this would mean
that the semantics of (:) would be different depending on whether the
slice is used as a slice or a range.

The next problem you run into is that the semantics of negative
numbers are completely different between slices and ranges.  Consider
this code:

s = (-5:6)
for i in s:
    print(i)
for i in range(6)[s]:
    print(i)

Intuitively, both loops should print the same thing.  After all, one
is using the slice s as a range, and the other is using the very same
slice s as a slice of a sequence where the indices and values are the
same.  This expectation fails, however.  The first loop prints the
integers from -5 to 5 inclusive, and the second loop only prints the
integers from 1 to 5 inclusive.

For these reasons, I disagree that allowing slices to be implicitly
converted to ranges or vice versa is a good idea.

> This is not a new idea: eg: 2002. (which is still status OPEN).
> http://osdir.com/ml/python.patches/2002-06/msg00319.html

It's not still open.  What you've linked above is an archived mailing
list message concerning the patch.  I've linked the actual tracker
issue that the patch was attached below; it was rejected by Guido in
2002.
http://bugs.python.org/issue575515



More information about the Python-list mailing list