Search code examples
wolfram-mathematica

Replace 2nd part of list returned with function squared


As mentioned above, I want to replace the 2nd part of a list returned from a function with the 2nd part squared.

n[s]:= {1*s,2*s};
ReplacePart[n[s],2->?^2]

I need the question mark to equal the current value returned. What is the most concise way of doing this with or without ReplacePart?


Solution

  • Perhaps

    n[s]:= {1*s,2*s}; 
    n[s]/.{y_,z_}->{y,z^2}
    

    which returns {s,4s^2}

    You can also write that as

    ReplaceAll[n[s],{y_,z_}->{y,z^2}]
    

    If the list may or may not have more than two elements then

    ReplaceAll[n[s],{y_,z_,x___}->{y,z^2,x}]
    

    will maintain any additional elements unchanged