[Tutor] reduce with comprehension

Brian van den Broek broek at cc.umanitoba.ca
Mon Nov 21 10:28:45 CET 2005


János Juhász said unto the world upon 2005-11-21 01:20:
> Hi,
> 
> I can't imagine how this could be made with list comprehension.
> 
> 
>>>>import operator
>>>>a = (([1],[2],[3,31,32],[4]), ([5],[6],[7, 71, 72]), ([8],[9]))
>>>>reduce(operator.add, a) # it makes a long list now
> 
> ([1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9])
> 
> When I make list comprehension, the list hierarchy is allways the same or
> deeper than the original hierarchy. But now it should be reduced with one
> level.
> 
> 
> 
>>>>[item for item in a] # the deepnes is the same
> 
> [([1], [2], [3, 31, 32], [4]), ([5], [6], [7, 71, 72]), ([8], [9])]
> 
>>>>[(item, item) for item in a] # it is deeper with one level
>>>>
> 
> 
> 
> Is it possible to substitute reduce with comprehension anyway ?
> 
> 
> Yours sincerely,
> ______________________________
> János Juhász
> 

Hi János,

I think it is.

 >>> a = (([1],[2],[3,31,32],[4]), ([5],[6],[7, 71, 72]), ([8],[9]))
 >>> b = []
 >>> [b.extend(x) for x in a]
[None, None, None]
 >>> b
[[1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]]


But don't do that :-)  Seems very poor form to me, as the desired 
operation is a side effect of the creation of the list via the 
comprehension.

If, however, you are just trying to avoid reduce:

 >>> b=[]
 >>> for x in a:
	b.extend(x)

	
 >>> b
[[1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]]
 >>>

Notice, too, that these ways result in a list of lists, whereas yours 
provided a tuple of lists.

HTH,

Brian vdB



More information about the Tutor mailing list