Python Forum

Full Version: How do i multiply elements in a list together
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How can I multiply all elements in a list together with a for loop?
What have you tried?
Edit: zip is not required for this task, because you've only one list.

If you have two Iterables (sequences), you can use the builtin function zip together with a for-loop or a list-comprehension. This are the building-blocks. In the for-loop you multiply one element from the first list, with one element on the second list. Then you append each result to a new list. In the case if you use a list-comprehension, the empty list is not needed and the code shrinks, because you don't need define an empty list and you don't need to append. For simple tasks, the list-comprehension is very handy. If you've a complex situation (catching Exceptions, branching, ...) a for-loop may be better.
@DeaD_EyE, OP wants to multiply all elements in single list (reduce) not two iterables
Edit: Sorry, in this case it's called Broadcasting and you don't need the zip, because the value you use to multiply, does not change. But it's still important to know the zip-function for future tasks.

So this task don't require the zip and a list-comprehension is the ideal candidate for this.
Btw: The solution is in the Python-Documentation: https://docs.python.org/3/tutorial/datas...rehensions
It took me one year to understand the structure of this document :-D
Although list comprehension is great tool, it's not what OP wants :-)
Sorry, Dead_EyE, I don't mean to snap, but obviously OP is confused enough and you are not helping by suggesting list comprehension.

(Mar-08-2020, 11:13 AM)Olavv Wrote: [ -> ]How can I multiply all elements in a list together with a for loop?
from their question, if they have [1, 2, 3] the result they look for is 1*2*3, i.e. 6

And because this looks very much like homework we don't give the solution without effort from OP
(Mar-08-2020, 12:17 PM)buran Wrote: [ -> ]Although list comprehension is great tool, it's not what OP wants :-)
Sorry, Dead_EyE, I don't mean to snap, but obviously OP is confused enough and you are not helping by suggesting list comprehension.

(Mar-08-2020, 11:13 AM)Olavv Wrote: [ -> ]How can I multiply all elements in a list together with a for loop?
from their question, if they have [1, 2, 3] the result they look for is 1*2*3, i.e. 6

And because this looks very much like homework we don't give the solution without effort from OP
It's okay. I figured it out