Multiplying 1D Array in Python

Question:

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.

Asked By: cia09mn

||

Answers:

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]“.

Answered By: Matthew Adams

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)
Answered By: João Silva

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
Answered By: Guy Adini
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.