Home > Software engineering >  Creating duplicates in a python list
Creating duplicates in a python list

Time:01-20

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

CodePudding user response:

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]

CodePudding user response:

If you want to do it in-place (i.e. without creating a separate list), you can insert each number at its position in a loop. However, the list indexes will change as you insert new items so, performing the insertions backwards will ensure that the remaining items to process are at their expected positions:

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

for i in reversed(range(len(list1))):
    list1.insert(i,list1[i])

print(list1)
[2, 2, 4, 4, 5, 5, 1, 1, 7, 7, 8, 8, 2, 2, 9, 9]
  •  Tags:  
  • Related