Multiply each element in a list by a number in Python

Borislav Hadzhiev

Last updated: Jul 9, 2022

Photo from Unsplash

**To multiply each element in a list by a number:**

- Use a list comprehension to iterate over the list.
- On each iteration, multiply the current element by the number.
- The new list will contain the multiplication results.

main.py

`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`

.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

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:**

- Declare a new variable that stores an empty list.
- Use a
`for`

loop to iterate over the original list. - On each iteration, multiply the current list item by the number.
- Append the result to the new list.

main.py

`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.

main.py

`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.

The lambda function we passed to

`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.

main.py

`import numpy as np arr = np.array([2, 4, 6]) result = arr * 10 print(result) # 👉️ [20 40 60]`

Multiplying a numpy array by a number effectively multiplies each element in the array by the specified number.

Note that this only works with numpy arrays. If you multiply a python list by a number, it gets repeated N times.

main.py

`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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

You can use the search field on my Home Page to filter through all of my articles.