Using the "i-=smallest" statement in the code below, I intend to alter my original array arr, but that isn't happening. What do I do?
<p>Here's the code:</p>

<pre><code>n = int(input())
arr = input().split()
arr = [int(x) for x in arr]
smallest = 1001
while(True):
    if smallest==0:
        break
    arr.sort()
    count = 0
    smallest = arr[0]
    for i in arr:
        if i==0:
            arr.remove(i)
        i-=smallest           #This statement.
        count+=1
    print(count)
</code></pre>

<p>For input:
(n=)6 and
(arr=)5 4 4 2 2 8
The output I'm getting is:
    6
    6
    6...
However, according to me, if my logic works (and the aforementioned statement actually edits my original array elements), the output should turn out to be
    6
    4
    2
    1
instead.</p>

<p>I might have got whole of the thing wrong. I'm an amateur. Any sort of help is appreciated.</p>

<p>Let's look at the inside loop</p>

<pre><code>for i in arr:
    if i==0:
        arr.remove(i)
    i-=smallest
    count+=1
</code></pre>

<p>It assigns the first value in <code>arr</code> to <code>i</code>. Since no value of the array is zero, it doesn't remove anything from the list. </p>

<p>It then reassigns the value of i by subtracting the smallest value. For the first time through the loop it assigns the value of zero to i. Then it increments count. The list <code>arr</code> is unchanged. The line <code>i=-smallest</code> has no effect since <code>i</code> is reassigned to the next value of the list.</p>

<p>So, with the values 5 4 4 2 8 8 (none of which are zero) that loop is equivalent to</p>

<pre><code>for i in arr:
    count+=1
</code></pre>

<p>Which is why it always prints 6.  I'm not sure why you think it should print 6 4 2 1. I suspect you think the list is being changed, but that the line <code>if i==0</code> is always false.</p>

<p>Changing the object being iterated over in a for loop is guaranteed to confuse you. There is almost certainly a better way to achieve what you want. See for example <a href="http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python">Remove items from a list while iterating in Python</a></p>

python arrays python-3.x