Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to duplicate every occurrence of specific item in list

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading