[Tutor] Deleting an entry from a dictionary

Kent Johnson kent37 at tds.net
Wed Aug 3 16:40:57 CEST 2005


Smith, Jeff wrote:
> Ummm...that doesn't do what I asked.
> 
> pop is a linguistic idiom for
> 
> (val, mylist) = (mylist[-1], mylist[0:-1])

No, actually, not quite.

>From the docs:

s.pop([i])  	same as x = s[i]; del s[i]; return x

so val = mylist.pop(0) is the same as
val = mylist[0]
del mylist[0]

which, other than the fact that it mutates mylist instead of returning a new slice, is identical to what you asked for.

For example:
 >>> l=[1,2,3]
 >>> l.pop(0)
1
 >>> l
[2, 3]


The default value for i is -1 so val = mylist.pop() is equivalent to what you have above (again, other than mutating instead of slicing).

Kent

> 
> shift is the standard idiom for 
> 
> (val, mylist) = (mylist[0], mylist[1:])
> 
> but Python doesn't appear to offer this.
> 
> Jeff
> 
> -----Original Message-----
> From: Kent Johnson [mailto:kent37 at tds.net] 
> Sent: Wednesday, August 03, 2005 9:15 AM
> Cc: tutor at python.org
> Subject: Re: [Tutor] Deleting an entry from a dictionary
> 
> 
> Smith, Jeff wrote:
> 
>>Speaking of which, I note that there is a pop for lists but no shift.
>>Is there a Python idiom for this or is it just
>>    val = mylist.shift() =>    (val, mylist) = (mylist[0], mylist[1:])
>>which seems a little clumsy.
> 
> 
> val = mylist.pop(0)
> 
> Kent
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



More information about the Tutor mailing list