I am having trouble working with lists inside functions with Mathematica. Basically, I have a list of numbers and a special way to multiply them. I want to have a function that is able to create a product using the input variable list, which can vary in length. Basically, what I want is something like this:

prod[x__] := Product[x[[i]], {i, 1, Length[x]}]

However, when I try

prod[2, 3, 4, 5]

I get this:

prod[2, 3, 4, 5]

During evaluation of In[73]:= Length::argx: Length called with 4 arguments; 1 argument is expected.
During evaluation of In[73]:= Part::pkspec1: The expression i cannot be used as a part specification.
During evaluation of In[73]:= Part::partd: Part specification 2[[3,4,5,1]] is longer than depth of object.

Product[2[[3, 4, 5, i]], {i, 1, Length[2, 3, 4, 5]}]

Can anyone tell me what I am doing wrong here? Any help would be appreciated. I'm sure it is something simple, but I have looked and been unable to find an answer online.

  • 1
    $\begingroup$ The x above is actually a sequence of four things, not a single list with four elements. Contrast with: In[57]:= prod[x_] := Product[x[[i]], {i, 1, Length[x]}] In[58]:= prod[{2, 3, 4, 5}] Out[58]= 120 $\endgroup$ – Daniel Lichtblau Nov 5 at 15:23
  • 2
    $\begingroup$ Are you aware that the built-in function Times will do what you appear to want? Times[2, 3, 4, 5] will return 120. $\endgroup$ – m_goldberg Nov 5 at 15:28
  • $\begingroup$ Or if you actually have a List: Times @@ {2, 3, 4, 5} $\endgroup$ – Bob Hanlon Nov 5 at 16:05
  • $\begingroup$ @m_goldberg Yes, I know that the default method exists. I only made the example with multiplication because the example I have is similar but more complex, using normally ordered products of series instead of standard multiplication :) $\endgroup$ – Jude Quintero Nov 5 at 20:32
  • $\begingroup$ @DanielLichtblau Thanks, I'll try is and see what happens. $\endgroup$ – Jude Quintero Nov 5 at 20:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.