443,275 Members | 1,745 Online
Need help? Post your question and get tips & solutions from a community of 443,275 IT Pros & Developers. It's quick & easy.

# multiply utple or list

 P: n/a what is the best way to multiply a tuple or list by a given value exp. multiply (4, 5) by 2 => (8, 10) cheers jr Jul 18 '05 #1
4 Replies

 P: n/a Jim Red wrote: what is the best way to multiply a tuple or list by a given value exp. multiply (4, 5) by 2 => (8, 10) cheers jr i.e.: import operator [ operator.mul(x,2) for x in (4,5)] regards, Karl Jul 18 '05 #2

 P: n/a Jim Red wrote: what is the best way to multiply a tuple or list by a given value exp. multiply (4, 5) by 2 => (8, 10) something like this? import types def multiply_sequence(sequence, multiplier): new_sequence = map(lambda item: item*multiplier, sequence) if type(sequence) == types.TupleType: return tuple(new_sequence) elif type(sequence) == types.ListType: return new_sequence -- Pádraig Brady - http://www.pixelbeat.org Jul 18 '05 #3

 P: n/a > >>> import operator >>> [ operator.mul(x,2) for x in (4,5)] Why not simply * ? [ x * 2 for x in (4,5)] And you might surround it by tuple to gain a tuple tuple([ x * 2 for x in (4,5)]) Another way would be to use Numeric import Numeric a = Numeric.array((10,2), Numeric.Float32) a = a * 2 -- Regards, Diez B. Roggisch Jul 18 '05 #4

 P: n/a Diez B. Roggisch wrote: >>> import operator >>> [ operator.mul(x,2) for x in (4,5)] Why not simply * ? [ x * 2 for x in (4,5)] oops, of course. I had the map function in mind, which only accepts a function, but this would come to something like: li=(4,5) map(operator.mul, li, (2,)*len(li)) and is certainly worse then list comprehension :-) regards, Karl Jul 18 '05 #5

### This discussion thread is closed

Replies have been disabled for this discussion.