Hello Python Ideas,
To quote the tutorial, "List comprehensions provide a concise way to create
lists without resorting to use of map(), filter() and/or lambda.".
There are a couple of constraints in the above definition that I feel could
be overcome. For one thing, list comprehensions don't let you create
immutable sequences (such as a tuple) by design. For another, it does not
provide a concise alternative to reduce() function.
To address both of the above, I'd like to introduce tuple comprehensions,
which would work like so:
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>>> (weapon.strip() for weapon in freshfruit)
('banana', 'loganberry', 'passion fruit')
>>> import operator
>>> (operator.concat(_, weapon.strip()) for weapon in freshfruit)
As you can see, we use parenthesis instead of square brackets around the
In the first tuple comprehension, we create a true tuple with multiple
items. This might a tad more efficient, not to mention less verbose, than
applying the "tuple" function on top of a list comprehension.
In the second tuple comprehension, we use a reduce() function (specifically
operator.concat) to concatenate all of the fruit names. In particular, we
use the "_" variable (for lack of a better name) to track the running
outcome of the reduce() function.