sequence multiplied by -1

Emile van Sebille emile at fenx.com
Sat Sep 25 13:57:35 EDT 2010


On 9/25/2010 10:24 AM Terry Reedy said...
> On 9/25/2010 4:22 AM, Yingjie Lan wrote:
>> I noticed that in python3k, multiplying a sequence by a negative
>> integer is the same as multiplying it by 0, and the result is an
>> empty sequence.
>
> This is explicitly documented: "Values of n less than 0 are treated as 0
> (which yields an empty sequence of the same type as s).) I would have
> made this raise a ValueError, but someone must have had a use case for
> getting an empty sequence.

At least it's consistent with slicing not generating a ValueError ala

ActivePython 2.6.1.1 (ActiveState Software Inc.)
based on Python 2.6.1 (r261:67515, Dec  5 2008, 13:58:38)
[MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> ham = range(10)
 >>> ham[11:21]
[]


... which in version 3 behaves differently?

ActivePython 3.1.2.3 (ActiveState Software Inc.)
based on Python 3.1.2 (r312:79147, Mar 22 2010, 12:20:29)
[MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> ham = range(10)
 >>> ham[11:21]
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: sequence index must be integer, not 'slice'
 >>>


Oh wait -- it's a range thing...

 >>> ham[1:3]
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: sequence index must be integer, not 'slice'
 >>> ham
range(0, 10)
 >>> type(ham)
<class 'range'>
 >>> ham = list(range(10))
 >>> ham[11:21]
[]
 >>>


Well, that's annoying, but it is what xrange did and the docs do say 
range 3.0 is the old xrange 2.x and that the old range 2.x I've deployed.


Stutter-stepping-to-3.x-ly yrs,

Emile










More information about the Python-list mailing list