evaluation of list comprehensions in python
In trying to use a list comprehension to make a list given a conditional,
I see the following:
In [1]: mydicts = [{'foo':'val1'},{'foo':''}]
In [2]: mylist = [d for d in mydicts if d['foo']]
In [3]: mylist
Out[3]: [{'foo': 'val1'}]
In [4]: mydicts[1]['foo'] = 'val2'
In [5]: mydicts
Out[5]: [{'foo': 'val1'}, {'foo': 'val2'}]
In [6]: mylist
Out[6]: [{'foo': 'val1'}]
I've been reading the docs to try and understand this but have come up
with nothing so far, so I'll ask my question here: why is it that mylist
never includes {'foo': 'val2'} even though the reference in the list
comprehension points to mydict, which by In [6] contains {'foo': 'val2'}?
Is this because Python eagerly evaluates list comprehensions? Or is the
lazy/eager dichotomy totally irrelevant to this?
No comments:
Post a Comment