[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: Surprised by the command "del"

Steve Holden

3/1/2008 8:02:00 PM

K Viltersten wrote:
> I'm reading the docs and at 5.2 the del
> statement is discussed. At first, i thought
> i've found a typo but as i tried that
> myself, it turns it actually does work so.
>
> a = ["alpha", "beta", "gamma"]
> del a[2:2]
> a
>
> Now, i expected the result to be that the
> "beta" element has been removed. Obviously,
> Python thinks otherwise. Why?!
>
> Elaboration:
> I wonder why such an unintuitive effect has
> been implemented. I'm sure it's for a very
> good reason not clear to me due to my
> ignorance. Alternatively - my expectations
> are not so intuitive as i think. :)
>
It deletes all the elements referred to by the slice. But since 2-2==0,
there are zero elements in the slice, and the list is unchanged when all
zero of them have been deleted:

>>> a = ["alpha", "beta", "gamma"]
>>> a[2:2]
[]
>>>

You would have got the result you expected with

del a[2]

or

del a[2:3]

or

del a[-1]

or ...

Remember that slices are specified as half-open intervals. So a[m:n]
includes m-n elements, those indexed from m to n-1.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.hold...

1 Answer

K Viltersten

3/1/2008 9:34:00 PM

0

>> I'm reading the docs and at 5.2 the del
>> statement is discussed. At first, i thought
>> i've found a typo but as i tried that
>> myself, it turns it actually does work so.
>>
>> a = ["alpha", "beta", "gamma"]
>> del a[2:2]
>> a
>>
>> Now, i expected the result to be that the
>> "beta" element has been removed. Obviously,
>> Python thinks otherwise. Why?!
>
> Remember that slices are specified as half-open
> intervals. So a[m:n] includes m-n elements,
> those indexed from m to n-1.

Got it. Thanks!

--
Regards
Konrad Viltersten
--------------------------------
sleep - a substitute for coffee for the poor
ambition - lack of sense to be lazy