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

# Multiply a tuple by a constant

 P: n/a I often need to multiply a tuple by a constant and the methods I use now are not very pretty. The idea is to get a new tuple that is some factor times the start tuple, like 'newtup = .5 * oldtup'. Is there a slick way to do this? Jul 18 '05 #1
5 Replies

 P: n/a Jay Davis wrote: I often need to multiply a tuple by a constant and the methods I use now are not very pretty. The idea is to get a new tuple that is some factor times the start tuple, like 'newtup = .5 * oldtup'. Is there a slick way to do this? Not really slick, but it works: tuple(map(5 .__mul__, (1,2,3))) (5, 10, 15) The space after the 5 is necessary. Alternatively, you can wrap the constant in brackets: tuple(map((5).__mul__, (1,2,3))) (5, 10, 15) Peter Jul 18 '05 #2

 P: n/a These days list comprehensions are preferred: tuple([5*i for i in (1,2,3)]) (5, 10, 15) Jul 18 '05 #3

 P: n/a On Fri, 13 Feb 2004 02:20:06 -0800, Jay Davis wrote: I often need to multiply a tuple by a constant and the methods I use now are not very pretty. The idea is to get a new tuple that is some factor times the start tuple, like 'newtup = .5 * oldtup'. Is there a slick way to do this? I suggest looking at Numarray - a very convenient way of doing maths on sets of numbers. Of course if you don't do very much it's not worth doing this. http://www.stsci.edu/resources/softw...dware/numarray You can do things like: import numarray a = numarray.array( (1.,2.,5.,-46.) ) a *= 0.5 b = a + 3.4 Jeremy Jul 18 '05 #4

 P: n/a two ways: t=(1,2,3) newt=tuple(map(lambda x: x*0.5, t)) Note: apparently the map function is slated for deprication (to be replaced by list comprehension) List comprehension: t=(1,2,3) newt=tuple([x*0.5 for x in t]) -Larry Bates ----------------------------------------------------------- "Jay Davis" wrote in message news:1d**************************@posting.google.c om... I often need to multiply a tuple by a constant and the methods I use now are not very pretty. The idea is to get a new tuple that is some factor times the start tuple, like 'newtup = .5 * oldtup'. Is there a slick way to do this? Jul 18 '05 #5

 P: n/a dj********@yahoo.com (Jay Davis) wrote in message news:<1d**************************@posting.google. com>... I often need to multiply a tuple by a constant and the methods I use now are not very pretty. The idea is to get a new tuple that is some factor times the start tuple, like 'newtup = .5 * oldtup'. Is there a slick way to do this? You can always subclass tuple and redefine "*". Dunno if you would consider it slick enough. Michele Jul 18 '05 #6

### This discussion thread is closed

Replies have been disabled for this discussion.