0

I want to multiply a vector by a scalar by a cicle, i.e: x1=[2,3,4,5] and i want to multiply it by 2, so that i get, x1=2(x2), x2=[4,6,8,10]. I tried doing this:

def multiplicar_vector(x1):
    x2=[]
    for i in x1:
        x2[i] = (x1[i])*2
    print(x2)

But it doesn't work.

Mandera
  • 2,647
  • 3
  • 21
  • 26
  • Does this answer your question? [Multiply every element of a list by a number](https://stackoverflow.com/questions/35355739/multiply-every-element-of-a-list-by-a-number) – Sociopath Aug 19 '20 at 12:09

3 Answers3

1

If you want to use pure python, you would likely use a list comprehension.

x1 = [item * 2 for item in x2]

This is taking each item in the x2, and multiplying it by 2. The square brackets indicate that you want to make a list of the results. It's equivalent to:

x1 = []
for item in x2:
    x1.append(item * 2)

Really though, most people would use numpy when dealing with lots of vectors as it much faster and easier.

import numpy as np

x1 = np.array([1, 2, 3, 4])
x2 = 2 * x1
QuantumChris
  • 963
  • 10
  • 21
0

You can iterate through each item and multiply it

x1=[2,3,4,5]
N=2
x2 = [ x * N for x in x1]
print(x2)

Incase you want to use a predefined package. Convert your list vector type into a numpy vector array type and multiply.

import numpy as np
x1=[2,3,4,5]
N=2
my_array = np.array(x1)
x2 = my_array * N
print(x2)
High-Octane
  • 1,104
  • 5
  • 19
0

There is a python package that does this really well : numpy

import numpy as np

x2  = np.array(x1)*2
AlexisG
  • 2,476
  • 3
  • 11
  • 25