0

I have a problem which is similar to this.

Here I am trying to append 0 after every 5 in the list.

The below code does not update the length of the list and the output I get is [1,4,5,0,2,7,5,0,5] while desired output is [1,4,5,0,2,7,5,0,5,0]

mylist1 = [1,4,5,2,7,5,5]

for i in range(len(mylist1)):
    if mylist1[i] == 5:
         mylist1.insert(i+1,0)
print(f'output: {mylist1}')

I have to update in the same list mylist1.

gog
  • 10,367
  • 2
  • 24
  • 38
Anonymous
  • 13
  • 2

4 Answers4

0

Try this :

mylist1 = [1,4,5,2,7,5,5]

for i, value in enumerate(mylist1):
    if value == 5:
         mylist1.insert(i+1, 0)
print(f'output: {mylist1}')
Alex
  • 26
  • 4
  • As a general rule, you should not modify any iterable whilst you're enumerating it. In this particular case it works but if you were removing elements you'd find yourself in trouble – DarkKnight Oct 19 '22 at 07:53
0

Problem is when you insert an item into list, the list length changed. So your loop not iterate all items.

Try this:

mylist1 = [1, 4, 5, 2, 7, 5, 5]

list_index = 0
while list_index < len(mylist1):
    if mylist1[list_index] == 5:
        mylist1.insert(list_index + 1, 0)
        list_index = list_index + 1
    list_index += 1
print(f'output: {mylist1}')
Xu Qiushi
  • 1,111
  • 1
  • 5
  • 10
0

The list.insert method costs O(n) in time complexity, so calling it in a loop makes the overall time complexity O(n ^ 2).

To do this in linear time complexity, you can instead create a new list by iterating over the input list and appending 0 when seeing a 5.

output = []
for i in mylist1:
    output.append(i)
    if i == 5:
        output.append(0)

If you do want the original list changed, you can copy the new list to the original in-place:

mylist1[:] = output

Demo: https://replit.com/@blhsing/ProperGrownDatum

blhsing
  • 91,368
  • 6
  • 71
  • 106
0

You can safely iterate over your list in reverse like this:

mylist1 = [1, 4, 5, 2, 7, 5, 5]

for i in range(len(mylist1)-1, -1, -1):
    if mylist1[i] == 5:
        mylist1.insert(i+1, 0)

print(f'output: {mylist1}')
DarkKnight
  • 19,739
  • 3
  • 6
  • 22