Mar-08-2020, 11:13 AM
How can I multiply all elements in a list together with a for loop?
How do i multiply elements in a list together
|
Mar-08-2020, 11:13 AM
How can I multiply all elements in a list together with a for loop?
Mar-08-2020, 11:14 AM
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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Mar-08-2020, 11:57 AM
@DeaD_EyE, OP wants to multiply all elements in single list (reduce) not two iterables
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link Create MCV example Debug small programs
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
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link Create MCV example Debug small programs
Mar-09-2020, 10:06 AM
(Mar-08-2020, 12:17 PM)buran Wrote: Although list comprehension is great tool, it's not what OP wants :-)It's okay. I figured it out |
|