Borislav Hadzhiev
Last updated: Jul 9, 2022
Photo from Unsplash
To multiply each element in a list by a number:
my_list = [2, 4, 6] result = [item * 10 for item in my_list] print(result) # 👉️ [20, 40, 60]
We used a list comprehension to iterate over the list and multiplied each list
item by 10
.
On each iteration, we multiply the current list item by the specified number and return the result.
Alternatively, you can use a simple for
loop.
To multiply each element in a list by a number:
for
loop to iterate over the original list.my_list = [2, 4, 6] result = [] for item in my_list: result.append(item * 10) print(result)
The for
loop works in a very similar way to the list comprehension, but
instead of returning the list items directly, we append them to a new list.
You can also use the map()
function to multiply each element in a list.
my_list = [2, 4, 6] result = list(map(lambda item: item * 10, my_list)) print(result) # 👉️ [20, 40, 60]
The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.
map
gets called with each item in the list, multiplies the item by 10
and returns the result.The last step is to use the list()
class to convert the map
object to a
list
.
If you work with numpy arrays, you can directly use the multiplication operator on the array to multiply each of its elements by a number.
import numpy as np arr = np.array([2, 4, 6]) result = arr * 10 print(result) # 👉️ [20 40 60]
Note that this only works with numpy arrays. If you multiply a python list by a number, it gets repeated N times.
print([2, 4, 6] * 2) # 👉️ [2, 4, 6, 2, 4, 6]
Multiplying a Python list by N, returns a new list containing the elements of the original list repeated N times.