Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I multiply each element in a list by a number?

Tags:

python

list

I have a list:

my_list = [1, 2, 3, 4, 5] 

How can I multiply each element in my_list by 5? The output should be:

[5, 10, 15, 20, 25] 
like image 670
DJ bigdawg Avatar asked Feb 03 '16 00:02

DJ bigdawg


People also ask

How do you multiply each element of a list by a number in Python?

Multiply Two Python Lists by a Number Using a For Loop Python for loops allow us to iterate over over iterable objects, such as lists. We can use for loops to loop over each item in a list and then multiply by it by a given number.

How do you multiply an array by a number in Python?

multiply() in Python. numpy. multiply() function is used when we want to compute the multiplication of two array.

Can you multiply a list in Python?

Lists and strings have a lot in common. They are both sequences and, like pythons, they get longer as you feed them. Like a string, we can concatenate and multiply a Python list.


1 Answers

You can just use a list comprehension:

my_list = [1, 2, 3, 4, 5] my_new_list = [i * 5 for i in my_list]  >>> print(my_new_list) [5, 10, 15, 20, 25] 

Note that a list comprehension is generally a more efficient way to do a for loop:

my_new_list = [] for i in my_list:     my_new_list.append(i * 5)  >>> print(my_new_list) [5, 10, 15, 20, 25] 

As an alternative, here is a solution using the popular Pandas package:

import pandas as pd  s = pd.Series(my_list)  >>> s * 5 0     5 1    10 2    15 3    20 4    25 dtype: int64 

Or, if you just want the list:

>>> (s * 5).tolist() [5, 10, 15, 20, 25] 
like image 108
Alexander Avatar answered Sep 29 '22 14:09

Alexander