MathGroup Archive 1993

[Date Index] [Thread Index] [Author Index]

Search the Archive

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[5]:= l={x,z,y,0,0}
>>
>>Out[5]= {x, z, y, 0, 0}
>>
>>In[6]:=  l/.l[[Length[l] ]]->l[[Length[l] ]]+1
>>
>>Out[6]= {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[6] seperately...

In[1]:= l={x,z,y,0,0}

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

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

Out[2]= 0

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

Out[3]= 1

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

Out[4]= {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[5]:= ??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[5]:= ReplacePart[ l, Last[l] + 1, Length[l]]

Out[5]= {x, z, y, 0, 1}

Note that the value of l is unchanged.

In[6]:= l

Out[6]= {x, y, z, 0}

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

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

Out[7]= 0

In[8]:= l

Out[8]= {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