list(dict)
The other day there was a thread on comp.lang.python that started off by discussing a common problem: deleting keys from a dict while iterating over it causes an exception. In other words, the following code fails:
>>> d = {1: 2, 3: 4, 5: 6}
>>> for i in d: del d[i]
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
This is easily solved by replacing for i in d with for i in d.keys(). The former iterates over the keys one by one, while the later creates a list of keys first, then iterates over *that*; the list does not change during the loop or after deleting keys from the dictionary, so the error above does not occur.
However. In Python 3000 this is going to change. d.keys() will then return an iterator, and effectively produce the same result as for i in d; that is, an exception. This can be solved (in both 2.5 and 3.0) by forcing a list; e.g. for i in list(d.keys()).
Then someone pointed out that this can be written as for i in list(d) as well. I had not given this much thought before, but this would work as well, of course. It's just that list(d) strikes me as very counter-intuitive. I mean, it makes sense, in a way; if you can iterate over a dictionary's keys by doing for i in d, then list(d) would do just that: iterate over the keys, collect them in a list, and return that list. Except that list(d) kind of reads to me as, "convert a dictionary to a list", which is not what it does. The reverse operation does not work because of this; dict(list(d)) doesn't fly. Maybe iterating over a dictionary's items would have been a better choice, after all. :-/