How to duplicate every occurrence of specific item in list

Question:

A given list looks like this

list = [1,2,3,4,5,6,4,0]

I would like to duplicate every occurrence of 4

so the output looks like this:

[1,2,3,4,4,5,6,4,4,0]

I tried to do it like this:

def dup(list):
    counter = 0
    for value in list:
        if value == 4:
            print(counter,value)
            list.insert(counter,4)
        counter += 1

print(dup([1,2,3,4,5,6,4,0]))

I stumbled on a problem when I inserted int into a list index shifts with it. And I am stuck in an infinite loop of inserting 4

Also I would like the change to be done in place.

Asked By: antekkalafior

||

Answers:

l = []
for n in nums:
  l.append(num)
  if n == 4:
    l.append(4)

or inplace (you need to increment the counter twice)

i = 0
while i < len(nums):
  if nums[i] == 4:
    nums.insert(i, 4)
    i += 1
  i += 1
Answered By: Tom McLean
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.