Why is dictionary.keys() a list and not a set?

Fredrik Lundh fredrik at pythonware.com
Thu Nov 24 12:17:55 CET 2005

bonono at gmail.com wrote:

> These results make more sense. However, I am still puzzled :
> 1. why would d.keys()/d.values() only return one list element ? Why
> isn't it a list of 1M element of either the keys or values but items()
> is ?

"keys" returns a single list object which contains references to existing
key objects.  "items" has to create one million new pair objects (which
in turn hold references to existing key and value objects).

creating a new object is a lot more expensive than adding another
reference to an existing object

(in a fully GC:ed implementation, the cost is zero.  if you have a pointer
to an object, you have a reference to it.  in CPython, you need to adjust
the reference count, so the cost is a couple of machine instructions)


More information about the Python-list mailing list