[docs] [issue14836] Add next(iter(o)) to set.pop, dict.popitem entries.
Terry J. Reedy
report at bugs.python.org
Thu May 17 00:41:30 CEST 2012
New submission from Terry J. Reedy <tjreedy at udel.edu>:
There have been several requests for a set.get() (no args) or set.pick() method to get an item without deleting it as .pop() does. Probably the best answer is to use the simple generic composition next(iter(s)). The counter response is that it is hardly obvious and needs to be documented.
Suggesion: after the current
Remove and return an arbitrary element from the set. Raises KeyError if the set is empty."
add "Use next(iter(s)) to return an arbitrary element without removing it."
Then change the following to match.
Remove and return an arbitrary (key, value) pair from the dictionary.
popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem() raises a KeyError."
Remove and return an arbitrary (key, value) pair from the dictionary. Raises KeyError if the dict is empty. Use next(iter(d)) to return an arbitrary pair without removing it."
The old comment about destructively iterating over a dict as a set belongs more with set.pop if it is not removed.
The idiom works with all iterators, but there is no other place I can think of to put it, and it is not needed for sequences.
assignee: docs at python
nosy: docs at python, terry.reedy
stage: needs patch
title: Add next(iter(o)) to set.pop, dict.popitem entries.
versions: Python 2.7, Python 3.2, Python 3.3
Python tracker <report at bugs.python.org>
More information about the docs