[Python-ideas] Tuple Comprehensions

Mathias Panzenböck grosser.meister.morti at gmx.net
Mon Oct 10 04:51:01 CEST 2011


On 10/09/2011 10:57 PM, Karthick Sankarachary wrote:
> 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)
> 'bananaloganberrypassion fruit'
>

In addition to all previous remarks about the generator expression, what's wrong with the following?

 >>> import operator
 >>> xs=['banana', 'loganberry', 'passion fruit']
 >>> reduce(operator.concat,(x.strip() for x in xs))

>
>
> As you can see, we use parenthesis instead of square brackets around the comprehension.
>
> 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.
>
> Best Regards,
> Karthick Sankarachary
>
>




More information about the Python-ideas mailing list