views:

77

answers:

2

What exactly are views in Python3.1? They seem to behave in a similar manner as that of iterators and they can be materialized into lists too. How are iterators and views different?

+2  A: 

From what I can tell, a view is still attached to the object it was created from. Modifications to the original object affect the view.

from the docs (for dictionary views):

>>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
>>> keys = dishes.keys()
>>> values = dishes.values()

>>> # iteration
>>> n = 0
>>> for val in values:
...     n += val
>>> print(n)
504

>>> # keys and values are iterated over in the same order
>>> list(keys)
['eggs', 'bacon', 'sausage', 'spam']
>>> list(values)
[2, 1, 1, 500]

>>> # view objects are dynamic and reflect dict changes
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(keys)
['spam', 'bacon']

>>> # set operations
>>> keys & {'eggs', 'bacon', 'salad'}
{'bacon'}
cobbal
+1  A: 

I would recommend that you read this. It seems to do the best job of explaining.

As far as I can tell, views seem to be associated more with dicts and can be forced into lists. You can also make an iterator out of them, through which you could then iterate (in a for loop or by calling next)

inspectorG4dget