Multiply Each Element of a List Python

When you multiply each element of a list, you create a new list with each value from the original list multiplied by a specific number.

The for loop for multiplication

The simplest way to do it is to use them for a loop.

Each number inside a range is multiplied by 2 and added to a list.

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

The for loop to create a list of squares

We can quickly modify this example, so it’s going to add squared numbers to a list instead of multiplied. Just add another star inside the append function to create a squared number.

If you run the code you are going to have a list of squared values.

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

If you want numbers raised to the power of 3, you have to use x**3.

List comprehension

List comprehension is available in some programming languages, such as Python.

The common application of list comprehension is to make a new list as a result of the operation applied to each member of the original list, using a syntax that is more compact than with a standard loop.

The code from the previous examples for numbers can be written this way.

You can also use the lambda function to achieve the same result.

Using NumPy

Another way to multiply elements of a list is to use the NumPy library.

This code is going to create a NumPy array and then it will be multiplied by 2.

[ 0  2  4  6  8 10 12 14 16 18]

Of course, using NumPy for such a simple example doesn’t make much sense. I just wanted to show you that this is also an option.