1
$\begingroup$

Assume that I have two lists like :

list1={1,2,3,4,5}; list2={a,b,c,d,e};

I want to replace some elements from list1 into list2 and make a new list, NewList. For example, I want to replace the elements of list1 from position 1 and 5, with the elements of list2 with the same positions. The result will be :

NewList={1,b,c,d,5};

Is there any way to do that ?!

$\endgroup$

3 Answers 3

6
$\begingroup$

Another way, doing it all at once:

Newlist = list2;    
Newlist[[{1,5}]] = list1[[{1,5}]];

Gives

Newlist
   (* {1, b, c, d, 5} *)
$\endgroup$
1
  • $\begingroup$ It's a nice and easy method! Thank you. $\endgroup$
    – Shellp
    Mar 31, 2014 at 11:27
2
$\begingroup$
list1 = {1, 2, 3, 4, 5};
list2 = {a, b, c, d, e};

NewList = list2;
NewList[[1]] = list1[[1]];
NewList[[5]] = list1[[5]];
NewList

{1, b, c, d, 5}

$\endgroup$
1
$\begingroup$
Newlist = ReplacePart[#2, Rule @@@ Transpose[{#3, #1[[#3]]}]] &[list1, list2, {1, 5}]
$\endgroup$
0

Your Answer

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

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