Home > OS >  Append 0 after specific element in the same list by updating the length using python
Append 0 after specific element in the same list by updating the length using python

Time:10-19

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.

CodePudding user response:

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}')

CodePudding user response:

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}')

CodePudding user response:

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

CodePudding user response:

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}')
  • Related