multiply utple or list

J

Jim Red

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
 
P

P

Jim said:
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
 
K

Karl Scalet

Diez said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,183
Messages
2,570,966
Members
47,516
Latest member
ChrisHibbs

Latest Threads

Top