2
$\begingroup$

I wrote a For Loop. In this For Loop, I want to change the values of a list. The main issue is:

I have a nested list like:

data={{{3941, 6870}, {3922, 6869}}, {{4022, 6869}, {4041, 6870}}, {{4066, 
   6869}, {4041, 6870}}, {{4097, 6868}, {4103, 6867}}, {{4103, 
   6867}, {4097, 6868}}}

I want to replace the first 2 (or 3) elements with other values

data /. data[[1 ;; 2]] ->  {{{3841, 6870}, {3822, 6869}}, {{3922, 
     6869}, {3941, 6870}}}

Unfortunalty, this ReplaceAll doesn't work, my output is:

{{{3941, 6870}, {3922, 6869}}, {{4022, 6869}, {4041, 6870}}, {{4066, 
   6869}, {4041, 6870}}, {{4097, 6868}, {4103, 6867}}, {{4103, 
   6867}, {4097, 6868}}}

Who can tell me what I do wrong?

$\endgroup$
1

2 Answers 2

4
$\begingroup$

One way is not using ReplaceAll, but

data[[1 ;; 2]] = {{{3841, 6870}, {3822, 6869}}, {{3922, 6869}, {3941, 
6870}}}

which overwrites the first two elements. The remainder of the list remains the same.

$\endgroup$
2
$\begingroup$
Clear["Global`*"]

data = {{{3941, 6870}, {3922, 6869}}, {{4022, 6869}, {4041, 6870}}, {{4066, 
     6869}, {4041, 6870}}, {{4097, 6868}, {4103, 6867}}, {{4103, 6867}, {4097,
      6868}}};

new = {{{3841, 6870}, {3822, 6869}}, {{3922, 6869}, {3941, 6870}}};

Either

data2 = Join[new, data[[Length[new] + 1 ;;]]];
    

Or

data3 = ReplacePart[data, Thread[Range[Length[new]] -> new]];
    

The methods are equivalent

data2 === data3

(* True *)
$\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.