Duplicate each member in a list

ariel picture ariel · Mar 15, 2010 · Viewed 31k times · Source

I want to write a function that reads a list [1,5,3,6,...] and gives [1,1,5,5,3,3,6,6,...]. Any idea how to do it?

Answer

Dave Kirby picture Dave Kirby · Mar 15, 2010
>>> a = range(10)
>>> [val for val in a for _ in (0, 1)]
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9]

N.B. _ is traditionally used as a placeholder variable name where you do not want to do anything with the contents of the variable. In this case it is just used to generate two values for every time round the outer loop.

To turn this from a list into a generator replace the square brackets with round brackets.