0

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.

Community
  • 1
  • 1
  • Possible duplicate of [Remove items from a list while iterating](https://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating) – DeepSpace Oct 30 '17 at 15:35
  • That doesn't really answer my question. I know there are different ways to remove an element by index. I want to know, why this duplicate is being added to the end of the list. –  Oct 30 '17 at 15:58

1 Answers1

0

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.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
  • I don't want to use del for this specific example because I want to be able to recreate this process without built-in functions. Del does the same goal that I am trying to achieve: select the desired index, remove that index, and move all the other elements up one index. That's what I am trying to reproduce. –  Oct 30 '17 at 16:00
  • @Dexstrum but you're not *moving* anything... you're *copying* the values which means the two at the end are going to be the same until you remove the end item as Zero says... Nothing is being *added*... To see what's happening just add a `print(lst)` at the start of your `for`-loop and watch what happens to it... – Jon Clements Oct 30 '17 at 16:05
  • And that's the answer I needed. I didn't realize that I was just copying and not moving anything. –  Oct 30 '17 at 16:07