Repeat Item in List x Number of Times

I have a basic question re. Lists

If I have a list
set example to {a,b,c,d,e}

And I want to create a new list, with each item in example list repeated x number of times, is there an easy way to do this?

So, if x = 3, then new_list would be {a,a,a,b,b,b,c,c,c,d,d,d,e,e,e,}

Hi.

Fairly easy:

set example to {"a", "b", "c", "d", "e"}
set x to 3

set new_list to repeatListItems(example, x)

on repeatListItems(originalList, x)
	set newList to {}
	repeat with thisItem in originalList
		set thisItem to thisItem's contents -- Resolve the reference.
		repeat x times
			set end of newList to thisItem
		end repeat
	end repeat
	
	return newList
end repeatListItems

Thats brilliant, thank you!
Really struggled to get my head around this one, and learnt a couple of new things from that solution, too.

In reading and learning about Applescript, I often see Nigel’s script written as follows:

set example to {"a", "b", "c", "d", "e"}
set x to 3

set new_list to repeatListItems(example, x)

on repeatListItems(originalList, x)
	set newList to {}
	repeat with i from 1 to (count originalList)
		set thisItem to (item i of originalList)
		repeat x times
			set end of newList to thisItem
		end repeat
	end repeat
	
	return newList
end repeatListItems

Is one method or the other preferable in some way or is this simply a matter of style? Thanks.

In this particular case, it’s simply what occurred to me as I was writing the script. :slight_smile: Either form will do here. If the original list contained hundreds or thousands of items, I might do a bit more experimenting to see if either was more conducive to being sped up!

Thanks Nigel; I appreciate the response.