slice notation as values?

Antoon Pardon apardon at forel.vub.ac.be
Mon Dec 12 04:38:16 EST 2005


Op 2005-12-10, Brian Beck schreef <exogen at gmail.com>:
> Antoon Pardon wrote:
>> Will it ever be possible to write things like:
>> 
>>   a = 4:9
>
> I made a silly recipe to do something like this a while ago, not that 
> I'd recommend using it. But I also think it wouldn't be too far-fetched
> to allow slice creation using a syntax like the above...

The point is that the syntax "4:9" is already used for slice creation.

The python grammer is essentally saying that something like 4:9 is a
literal, just like strings and numbers, but that this specific literal
can only be used in a subscription.

Look at the following:

>>> import dis
>>> def foo():
...     lst[[2,3,5]]
...     lst[8:13:21]
... 
>>> dis.dis(foo)
  2           0 LOAD_GLOBAL              0 (lst)
              3 LOAD_CONST               1 (2)
              6 LOAD_CONST               2 (3)
              9 LOAD_CONST               3 (5)
             12 BUILD_LIST               3
             15 BINARY_SUBSCR       
             16 POP_TOP             

  3          17 LOAD_GLOBAL              0 (lst)
             20 LOAD_CONST               4 (8)
             23 LOAD_CONST               5 (13)
             26 LOAD_CONST               6 (21)
             29 BUILD_SLICE              3
             32 BINARY_SUBSCR       
             33 POP_TOP             
             34 LOAD_CONST               0 (None)
             37 RETURN_VALUE        

So you see that the slice is treated in an similar way
as the list. There is no reason why this shouldn't work
in case we want a slice in an assignment or a function
call.

-- 
Antoon Pardon



More information about the Python-list mailing list