Search code examples
pythonpython-2.7listfor-loopdel

Duplicate element being added through for loop


NOTE: I do not want to use del

I am trying to understand algorithms better which is why I want to avoid the built-in del statement.

I am populating a list of 10 randomly generated numbers. I then am trying to remove an item from the list by index, using a for loop:

if remove_index < lst_size:
   for value in range(remove_index, lst_size-1):
        lst[value] = lst[value+1]
    lst_size -= 1

Everything works fine, except that the loop is adding the last item twice. Meaning, if the 8th item has the value 4, it will add a 9th item also valued 4. I am not sure why it is doing this. I still am able to move the value at the selected index (while moving everything up), but it adds on the duplicate.


Solution

  • Nothing is being added to your list. It starts out with lst_size elements, and, since you don't delete any, it retains the same number by the time you're done.

    If, once you've copied all the items from remove_index onwards to the previous index in the list, you want to remove the last item, then you can do so either using del or lst.pop().

    At the risk of sounding flippant, this is a general rule: if you want to do something, you have to do it. Saying "I don't want to use del" won't alter that fact.

    Merely decrementing lst_size will have no effect on the list - while you may be using it to store the size of your list, they are not connected, and changing one has no effect on the other.