views:

604

answers:

1

dict methods dict.keys(), dict.items() and dict.values() return “views” instead of lists. http://docs.python.org/dev/3.0/whatsnew//3.0.html

First of all how is a view different from an iterator? Secondly, what is the benefit of this change? Is it just for performance reasons?

It doesn't seem intuitive to me, i.e., I'm asking for a list of thing (give me all your keys) and I'm getting something else back. Will this confuse people?

+7  A: 

You are effectively getting a list. It's just not a copy of the internal list, but something that acts as if it where a list but only represents the internal state.

That's the same way it's implemented in Java (and probably many other languages/environments as well).

The main reason is that for many use cases returning a completely detached list is unnecessary and wasteful. It would require copying the entire content (which may or many not be a lot).

If you simply want to iterate over the keys then creating a new list is not necessary. And if you indeed need it as a separate list (as a copy) then you can easily create that list from the view.

Joachim Sauer