4
$\begingroup$

Probably very basic, sorry, but I've searched extensively without finding a solution:

list_2 = ReplacePart[list_1, _?EvenQ -> "Sin(value of the entry in this position in list_1)" ]

That is, creating list_2, for every second entry replace its value with the Sinus of the corresponding value in list_1.

So for example {1, pi/2} should return {1, 1}. What is the code I should use in "..."?

On a general note: How does one address the value of the "current position" in a list? Thanks.

$\endgroup$
0

3 Answers 3

6
$\begingroup$
list1 = {1, Pi/2, Pi, 3 Pi/2, 3, 10};

list2 = ReplacePart[list1, part_?EvenQ :> foo[list1[[part]]]]

{1, foo[π/2], π, foo[(3 π)/2], 3, foo[10]}

list3 = ReplacePart[list1, part_?EvenQ :> Sin[list1[[part]]]]

{1, 1, π, -1, 3, Sin[10]}

$\endgroup$
1
$\begingroup$
list = {1, Pi/2, Pi, 3 Pi/2, 3, 10};

With MapAt:

MapAt[Sin, 2 ;; ;; 2] @ list

{1, 1, Pi, -1, 3, Sin[10]}

Or ReplaceAt (since V 13.1):

ReplaceAt[x_ :> Sin[x], 2 ;; ;; 2] @ list

{1, 1, Pi, -1, 3, Sin[10]}

With ReplaceAt one can easily impose additional conditions:

ReplaceAt[x_ /; x > Pi :> Sin[x], 2 ;; ;; 2] @ list

{1, Pi/2, Pi, -1, 3, Sin[10]}

$\endgroup$
1
$\begingroup$

Another way using Cases:

list1 = {1, Pi/2, Pi, 3 Pi/2, 3, 10};
Cases[list1, p_ :> If[! OddQ[p], Sin[p], p]]

{1, 1, 0, -1, 3, Sin[10]}
$\endgroup$

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.