Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #51138 > unrolled thread
| Started by | Skip Montanaro <skip@pobox.com> |
|---|---|
| First post | 2013-07-24 09:58 -0500 |
| Last post | 2013-07-24 09:58 -0500 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Python 3: dict & dict.keys() Skip Montanaro <skip@pobox.com> - 2013-07-24 09:58 -0500
| From | Skip Montanaro <skip@pobox.com> |
|---|---|
| Date | 2013-07-24 09:58 -0500 |
| Subject | Re: Python 3: dict & dict.keys() |
| Message-ID | <mailman.5040.1374677910.3114.python-list@python.org> |
> What do you mean? Why would you want to create a temporary list just to
> iterate over it explicitly or implicitly (set, sorted, max,...)?
Because while iterating over the keys, he might also want to add or
delete keys to/from the dict. You can't do that while iterating over
them in-place.
This example demonstrates the issue and also shows that the
modification actually takes place:
>>> d = dict(zip(range(10), range(10, 0, -1)))
>>> d
{0: 10, 1: 9, 2: 8, 3: 7, 4: 6, 5: 5, 6: 4, 7: 3, 8: 2, 9: 1}
>>> for k in d:
... if k == 3:
... del d[k+1]
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
>>> for k in list(d):
... if k == 3:
... del d[k+1]
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
KeyError: 4
>>> d.keys()
dict_keys([0, 1, 2, 3, 5, 6, 7, 8, 9])
Skip
Back to top | Article view | comp.lang.python
csiph-web