Jump to content

What are some ways to perform multiplication on a list of integers using loops in Python?


Recommended Posts

Posted
If you mean multiplying all the list items by some common factor, list comprehension is quick and clean. It has the same for loop implication

li = [1, 2, 3, 4, 5] 
 
print([2*i for i in li]) 
 
#OUTPUT 
[2, 4, 6, 8, 10] 
If you rather mean multipling all the items together to get a product, you can still use a for loop such as

li = [1, 2, 3, 4, 5] 
 
total = 1 
 
for i in li: 
        total = total * i 
 
print(total) 
 
#OUTPUT 
120 

 

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...