[Python-ideas] List Comprehensions
Chris Angelico
rosuav at gmail.com
Wed Feb 3 06:14:34 EST 2016
On Wed, Feb 3, 2016 at 10:04 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> I've sometimes thought that Python should have a iterator concatenation
> operator (perhaps &) which we could use:
>
> [x for x in range(5) & [100] & "spam"]
> => returns [0, 1, 2, 3, 4, 100, 's', 'p', 'a', 'm']
Might be problematic for generic iterables, as your three examples
are; but if you explicitly request an iterator, it's not hard to make
it support + or & for chaining:
from itertools import chain
_iter = iter
class iter:
def __init__(self, *args):
self.iter = _iter(*args)
def __add__(self, other):
return type(self)(chain(self.iter, _iter(other)))
__and__ = __add__
def __iter__(self): return self
def __next__(self): return next(self.iter)
print(list(iter(range(5)) & [100] & "spam"))
Is that good enough?
ChrisA
More information about the Python-ideas
mailing list