I am working with the Mathematica S&P 500 data

datasp=Prepend[ExampleData[{"Statistics", "SP500"}],ExampleData[{"Statistics", "SP500"}, "ColumnHeadings"]];

and have to multiply every 20th element by 203.63. In a next step, I will have to calculate the sum of all elements from the list (including the elements that have not been multiplied).

Unfortunately, I am struggling a bit with this. Could anyone help me out?

Thanks in advance!


1 Answer 1


Keep track of your data by creating a new list, datasp1 = datasp;. Manipulate every 20th element of the new list, Table[datasp1[[i]] = 203.63 datasp1[[i]], {i, 20, Length@datasp, 20}] (notice that the step is set to 20 so every 20th element is changed; if you need to ignore the header, start at 21). Verify, datasp1[[40]]/datasp[[40]]. Sum them with Total@datasp1.

  • $\begingroup$ Thanks you're a hero! $\endgroup$
    – noob3000
    Feb 24, 2021 at 23:38
  • 6
    $\begingroup$ Another possibility is datasp1[[ ;; ;; 20]] *= 203.63. $\endgroup$
    – Carl Woll
    Feb 25, 2021 at 0:15
  • $\begingroup$ Carl, would you please explain how your code works? I neither understand how Span Span 20 produces a loop with a step of 20 nor how *= works in this setting. $\endgroup$
    – Nicholas G
    Feb 27, 2021 at 3:45
  • 1
    $\begingroup$ @NicholasG The syntax of Carl is short for datasp1[[ 1 ;; Length[datasp1] ;; 20 ]]. It says: take element 1 to Length[datasp1] in steps of 20. This line takes every 20th element of datasp1 and multiplies it by 203.63. For more info look up the documentation of Part $\endgroup$ Nov 9, 2022 at 20:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.