Strange behaviour of Set and Part when given a sequence

Consider this example:

lis1 = {a, b, c};
lis1[[2]] = Sequence[e, f];
lis1
(*{a, e, f, c}*)
lis1[[2]]
(*e*)
lis1[[2]] = Sequence[g, h];
lis1
(*{a, g, h, c}*)


It looks like position 2 in lis1 is still has head Sequence, yet no sign of Sequence in the full form of lis1.

Can any one explain why is this happening?

• Have a look at this. – Leonid Shifrin Sep 11 '14 at 21:33
• @LeonidShifrin, lis1 = DeleteCases[lis1, Sequence, -1]; will completely solve the problem but I get confused how to explain this because Sequence is a head and as far as I know you can not completely delete head but replace head by another head. – Algohi Sep 11 '14 at 21:58
• Read more carefully the linked explanation. In DeleteCases, Sequence disappears in lis1 as a result of evaluation. – Leonid Shifrin Sep 11 '14 at 22:05
• @LeonidShifrin thanks a lot. I got it now. – Algohi Sep 11 '14 at 23:00

I think this readily explained by looking at the own-values of the variable after the assignment is made.

v = {a, b, c}; v[[2]] = Sequence[e, f];
OwnValues @ v

{HoldPattern[v] :> {a, Sequence[e, f], c}}


It's rather like Defer, so it will behave like {a, e, f, c} under standard evaluation. But it can behave differently in non-standard evaluation. When this would be a problem, you can always do

v = v

{HoldPattern[v] :> {a, e, f, c}}


to get variable bound to the fully evaluated form.

• Set using non-standard evaluation wouldn't alone be enough to provide this behavior. The key here is that Set and SetDelayed (as well as Rule and RuleDelayed) are also SequenceHold. – Leonid Shifrin Sep 11 '14 at 22:08
• @LeonidShifrin. You're right. I did not mean to imply the Set alone was the culprit. Bad wording on my part. I will try to fix it. – m_goldberg Sep 11 '14 at 22:11
• No worries, I didn't mean that comment as a critique, just as an additional piece of information. – Leonid Shifrin Sep 11 '14 at 22:16