       Re: Lists

• To: mathgroup at yoda.physics.unc.edu
• Subject: Re: Lists
• From: twj
• Date: Fri, 29 Jan 93 08:26:47 CST

```Neilb writes

>but
>
>>In:= l={x,z,y,0,0}
>>
>>Out= {x, z, y, 0, 0}
>>
>>In:=  l/.l[[Length[l] ]]->l[[Length[l] ]]+1
>>
>>Out= {x, z, y, 1, 1}
>>
>which is curious. Does anybody know why
>this doesn't produce
>{x,y,z,0,1}?

Try to do the steps in In seperately...

In:= l={x,z,y,0,0}

Out= {x, z, y, 0, 0}

In:= l[[Length[l] ]]

Out= 0

In:= l[[Length[l] ]]+1

Out= 1

In:= {x, z, y, 0, 0} /. 0 -> 1

Out= {x, z, y, 1, 1}

Thus l[[Length[l]]] will evaluate to the last element in l.

A replacement rule based on this last element is then applied.

If any other elements match this last element they also will be changed.

Maybe the thing you really want is ReplacePart?

In:= ??ReplacePart

ReplacePart[expr, new, n] yields an expression in which the nth part of expr
is replaced by new. ReplacePart[expr, new, {i, j, ...}] replaces the part
at position {i, j, ...}. ReplacePart[expr, new, {{i1, j1, ...}, {i2, j2,
...}, ...}] replaces parts at several positions by new.

Attributes[ReplacePart] = {Protected}

In:= ReplacePart[ l, Last[l] + 1, Length[l]]

Out= {x, z, y, 0, 1}

Note that the value of l is unchanged.

In:= l

Out= {x, y, z, 0}

You can change the value of l by some strategy like...

In:= Part[ l, Length[l]]++

Out= 0

In:= l

Out= {x, y, z, 1}

Tom Wickham-Jones
WRI

```

• Prev by Date: Re: Lists
• Next by Date: re: Lists
• Previous by thread: Re: Lists
• Next by thread: re: Lists