Re: repeating elements in a list
- To: mathgroup at smc.vnet.net
- Subject: [mg54946] Re: [mg54878] repeating elements in a list
- From: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>
- Date: Tue, 8 Mar 2005 05:03:32 -0500 (EST)
- Sender: owner-wri-mathgroup at wolfram.com
>-----Original Message----- >From: Torsten Coym [mailto:torsten.coym at eas.iis.fraunhofer.de] To: mathgroup at smc.vnet.net >Sent: Saturday, March 05, 2005 7:34 AM >Subject: [mg54946] [mg54878] repeating elements in a list > >Hello, > >suppose I have list > >lst={A, B, C} > >and I want to create a new list, where all elements are >repeated n times >so that (for n=3): > >newlst={A, A, A, B, B, B, C, C, C} > >I have the following code to do this: > >n=3; >newlst=Flatten[Table[Table[lst[[i]], {n}], {i, Length[lst]}]]; > >but I'm pretty sure, that there must be a more elegant way to >solve the >problem. > > >thank you > > Torsten, I wouldn't consider your solution as unelegant, alt least it is quite clear. Instead of Table[ something[[i]], {i, Length[something], you may use (# &) /@ something: In[16]:= Join @@ (Table[#, {n}] &) /@ lst Out[16]= {A, A, A, B, B, B, C, C, C} (I used Join @@ expr instead of Flatten[ expr, 1] ) The preferred way to expand a list by repeated elements is PadLeft: So here, two ways to pad: In[8]:= Join @@ (PadLeft[{#}, n, #] &) /@ lst Out[8]= {A, A, A, B, B, B, C, C, C} In[15]:= Join @@ With[{ll = Partition[lst, 1]}, PadLeft[ll, {Length[ll], n}, ll]] Out[15]= {A, A, A, B, B, B, C, C, C} The last expression exploits the possibilities of the built-in function PadLeft, which normally is prefereable, as this recurses less to the Mathematica mainloop, avoiding all time-consuming checks therein. So I prefer this, but from the viewpoint of elegance? I just repeat my so often asked (but never answered) question: what is elegance? -- Hartmut Wolf