December 17th, 2013, 04:29 PM
i'm new to studying python and I admit I'm not far into my learning at all, but I want to keep up with it and something of an example confused me. I remember that the popitem method removes the last item of a sequence. My book provided the example:
I understand that key and value are now assigned here, but what I don't understand is why calling scoundrel produces 'name':'person'.
key, value = scoundrel.popitem()
Does popitem directly modify a list or tuple or what have you, or create a new copy? In either case, why did popitem remove the first index in scoundrel assignment, but when I tried
, I got a traceback error?
December 17th, 2013, 05:03 PM
Curly brace syntax makes scoundrel a dictionary. dict objects are unordered. scoundrel.popitem() removes an item from the dictionary as a (key, value) tuple. You do not know ahead of time which item will be removed. The dict popitem method reduces the len of the dictionary by 1.
A python list has a pop method which removes and returns the object at the tail of the list.
Immutable (unchanging) tuples do not have a pop method.
The python set type has a pop method. Like a dict object, a set is unordered. The pop method returns some object from the set and reduces the set len by 1.
dict objects are not callable. You cannot call scoundrel. "Calling scoundrel" means exactly scoundrel() . Nowhere did you show scoundrel() . dict objects have callable methods, such as popitem.
popitem bound to scoundrel takes no arguments. You gave it one.
Instead of writing all this, perhaps I should have just shown you this neat trick which you can use in the interpreter:
Help on built-in function popitem:
D.popitem() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty.
[/code] are essential for python code and Makefiles!
December 17th, 2013, 05:17 PM
i had no idea help was so interactive, i took it merely as help() and that was that. i knew there was something about randomness with dictionary popitem, but I still managed to confuse popitem() with what a list would have done. the random assignment answers the rest, thanks again guy