Services & Resources / Wolfram Forums
MathGroup Archive
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2005

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

Search the Archive

Re: repeating elements in a list

  • To: mathgroup at
  • Subject: [mg54946] Re: [mg54878] repeating elements in a list
  • From: "Wolf, Hartmut" <Hartmut.Wolf at>
  • Date: Tue, 8 Mar 2005 05:03:32 -0500 (EST)
  • Sender: owner-wri-mathgroup at

>-----Original Message-----
>From: Torsten Coym [mailto:torsten.coym at] 
To: mathgroup at
>Sent: Saturday, March 05, 2005 7:34 AM
>Subject: [mg54946] [mg54878] repeating elements in a list
>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:
>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 
>thank you


I wouldn't consider your solution as unelegant, alt least it is quite

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}

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

  • Prev by Date: Re: repeating elements in a list
  • Next by Date: Re: Outputing a tabular function
  • Previous by thread: Re: repeating elements in a list
  • Next by thread: Kernel Problem