Creating duplicates in a python list

I want to repeat numbers in a list but I'm not sure how to start. Here's an example of what I'm looking to do

list1=[2,4,5,1,7,8,2,9]

list_I_want=[2,2,4,4,5,5,1,1,7,7,8,8,2,2,9,9]

I was thinking probably a for loop to do this but I am not sure where to start


Solution 1:

Here's an easy method using nested loops in a list comprehension:

>>> list1=[2,4,5,1,7,8,2,9]
>>> [i for i in list1 for _ in range(2)]
[2, 2, 4, 4, 5, 5, 1, 1, 7, 7, 8, 8, 2, 2, 9, 9]

This is equivalent to doing nested for loops and appending in the inner loop:

>>> list_i_want = []
>>> for i in list1:
...     for _ in range(2):
...         list_i_want.append(i)
...
>>> list_i_want
[2, 2, 4, 4, 5, 5, 1, 1, 7, 7, 8, 8, 2, 2, 9, 9]