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.
1 2 3 4 5 6 |
numbers = [] for x in range(10): numbers.append(x*2) print(numbers) |
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.
1 2 3 4 5 6 |
squares = [] for x in range(10): squares.append(x**2) print(squares) |
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.
1 2 |
numbers = [x*2 for x in range(10)] print(numbers) |
You can also use the lambda function to achieve the same result.
1 2 |
numbers = list(map(lambda x: x*2, range(10))) print(numbers) |
Using NumPy
Another way to multiply elements of a list is to use the NumPy library.
1 2 3 4 5 6 7 |
import numpy numbers = range(10) numpy_array = numpy.array(numbers) new_array = numpy_array * 2 print(new_array) |
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.