Removing negative values and printing the original and the new list
<p>To start of I am telling you this is for school as I am learning to code with Python. Please do explain why I should do something :)! I am looking to learn not just getting the answer.</p>

<p>I am trying to get rid of the negative items in the list. I want to print the list Before (including the negative items) and after ( without the negative items of course). 
My problem is that it prints out the original list and the new list without negative items on the Before print and the original one on After. 
Like this: </p>

<pre><code>Before: [2, 7, -3, -3, 13, -14, 13, 5, 11, -4, 10, 5, 0, -5, -14,
-2, -9, -14, 2, -10, -5, 8, 7]
[2, 7, 13, 13, 5, 11, 10, 5, 0, 2, 8, 7]
After: [2, 7, -3, -3, 13, -14, 13, 5, 11, -4, 10, 5, 0, -5, -14, -2, -9,
-14, 2, -10, -5, 8, 7] 
</code></pre>

<p>This is what I've done and I just can't seem to figure out what I should do...</p>

<pre><code>import random

def removeNegatives(listOfIntegers):
    l = listOfIntegers[:]           #takes a copy of the list
    for item in listOfIntegers:     
        if item &lt; 0:                #checks if it is lower than 0
           l.remove(item)
    print l



l = []
for i in xrange(0, random.randint(15,25)): #gives me the random numbers
  l.append(random.randint(-15,15))

print "Before:", l #should only print out the original list of numbers
removeNegatives(l)
print "After:", l #should only print out the new list without the numbers that are &lt;0
</code></pre>

<p>The "cleanest" way to modify external list will be to change its contents without reassigning - which changes list object reference. You can't remove elements when looping over list, and removing each non-compliant element while iterating over copy is very ineffective. </p>

<p>But you may reassign contents of list without re-assigning list object reference - using <strong>slice</strong> on the left side of the assignment</p>

<pre><code>def removeNegatives(listOfIntegers):
    listOfIntegers[:] = filter(lambda x: x &gt;= 0, listOfIntegers)
</code></pre>

<p>This code creates new list of non-negative values, and replaces whole content of the external-scope list.</p>

python python-2.7