1

If I have a 1D array in Python for example:

a = (10,20,30,40,50)

How can I multiply this by an integer for example 2 to produce:

b = (20,40,60,80,100)

I have tried:

b = a*2 

But it doesn't seem to do anything.

Sicco
  • 6,167
  • 5
  • 45
  • 61
cia09mn
  • 23
  • 3

3 Answers3

3

Tuples are immutable; use lists ([] instead of ()) if you're going to want to change the contents of the actual array.

To make a new list that has elements twice those of the tuple, loop over the tuple and multiply each element:

b = []
for num in a:
    b.append(2*num)

This can be shortened to

b = [2*num for num in a]

using list comprehensions.

Note that If you really want the final result to still be a tuple, you can use use

b = tuple([2*num for num in a])

I believe the closest thing you can get to your original syntax without using third party libraries would be

>>> map(lambda n: n*2, [1,2,3])
[2, 4, 6]

which is basically just a fancy way of saying, "take the function f(n) = 2n and apply if to the list [1,2,3]".

Matthew Adams
  • 9,426
  • 3
  • 27
  • 43
  • Tuples are not the problem here. The end result of using a list instead of a tuple is the same in terms of the elements: `[10, 20, 30, 40, 50, 10, 20, 30, 40, 50]`. -1 – Matt Ball Sep 01 '12 at 14:55
  • @MattBall Totally right. (I clicked submit before enough of my answer was down.) – Matthew Adams Sep 01 '12 at 15:03
  • 1
    map function doesn't modify the list, it just returns a new one. – MatthieuW Sep 01 '12 at 15:19
  • @MatthieuW True. I wrote that, thought about it for a second, and then realized I was being kinda stupid. Also, everyone involved in this question now has some form of the name Matthew... – Matthew Adams Sep 01 '12 at 15:34
3

Use the following:

>>> b = [2 * i for i in a]
>>> b
[20, 40, 60, 80, 100]

a * 2 will duplicate your set:

>>> a = (10,20,30,40,50)
>>> a * 2
(10, 20, 30, 40, 50, 10, 20, 30, 40, 50)
João Silva
  • 89,303
  • 29
  • 152
  • 158
3

For a more natural way of working with numbers, you may want to consider numpy. Using numpy, your code would like like this:

import numpy as np
a = np.array([10,20,30,40,50])
b = a*2
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Guy Adini
  • 5,188
  • 5
  • 32
  • 34