why won't slicing lists raise IndexError?

Rick Johnson rantingrickjohnson at gmail.com
Tue Dec 5 07:31:30 EST 2017


Ned Batchelder wrote:
[...]
> Your original statement sounded like, "The else clause can
> never be executed," 

No. Of course not. Note that i mentioned _pragmatism_. My
complaint about the else-clause was not that it could
_never_ be executed, my complaint that was that the else-
clause (in Terry's example) serves no useful purpose save to
act as a semantical placeholder for a non-action. Heck, it
doesn't even log anything! "Practicality beats purity". For
instance:
 (1) Would it be practical to make a shopping list that
 includes only the products you _don't_ want to buy?
 
 no ham
 no eggs
 no spam
 no Limburger
 
 "Okay, but what do we _need_!!!"
 
 (2) How about a list of navigation directions that includes
 tangential info?
 
 "After you take the second left turn, you'll see a big
 windmill -- just ignore that"
 (3) How about a recipe that includes non-ingredients?
 
 1 egg
 2 pounds of ham
 0 teaspoons coarse sea-salt
 0 cups of finely shreded Limburger
 ...
> which would have been in direct opposition to the point,
> that slicing outside the limits would produce an empty
> list, not an exception.

And again, that is precisely why i raised an objection to
this else-clause. Because the inclusion of this else-clause
is a distraction from the point.
> I'm not sure why you are certain that there's never a
> reason to execute code in that case.

Oh, there will be a _reason_ for else-clause to execute
(when the slice overlaps the boundary), but i argue the code
contained within is not a _good_ reason for it to execute.
 item = seq[n:n+1]
 if item:
 process(item)
 else:
 do_without_item()
 
"do_without_item()" implies a non-action. However, that's
not to say that under different circumstances, the else-
clause might serve a practical purpose for a programmer. For
instance, even a logging event serves a purpose.
 ss, se = n, n+1
 item = seq[ss:se]
 if item:
 process(item)
 else:
 print('Slice ({0}, {1}) out of bounds!'.format(ss, se))
> Perhaps I have a simulation on a conceptually infinite
> line, but only store the actual points needed. The "non
> action" would be to extend the line.

That logic does not follow! How do you _extend_ an infinite
line? :-). Of course, in the realm of maths, a line is by
definition infinite.
But whether you're speaking in metaphor or not, there are
literally infinite ways in which an else-clause can be
justified. My argument was simply: "do_without_item()" is
not a legitimate justification.


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /