[Python-ideas] Add single() to itertools

Ivan Pozdeev vano at mail.mipt.ru
Mon Oct 30 00:14:10 EDT 2017

The eponymous C#'s LINQ method, I found very useful in the following, 
quite recurring use-case:

I need to get a specific element from a data structure that only 
supports search semantics (i.e. returns a sequence/iterator of results).
For that, I specify very precise search criteria, so only that one item 
is supposed to be found. But I'd rather verify that just in case.

"A data structure that only supports search semantics" is a recurring 
phenomenon due to this:

I make a special-purpose data structure (usually for some 
domain-specific data like task specification or data directory) using a 
combination of existing and/or new containers. Now, these types do not 
enforce all the integrity constraints of my data. And I don't wish to 
construct a special-purpose class, complete with validation procedures, 
and pass records into it one by one etc -- when I can just write an 
initializer, loading all the data at once in a nicely readable 
construct, and call it a day.

So, when querying this structure, I "know" that there should only be one 
item satisfying a certain criteria - if there's more, or less, something 
is wrong with the data.

is the most recent occasion where I had this use case (that is not 
Python but the concept is language-agnostic).


More information about the Python-ideas mailing list