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>Just saw your comment relative to not being able to modify the code below l = []</p>

<p>In that case, you need to reassign to listOfIntegers coming out of your function</p>

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

<p>You make a copy of the global as you come in the function, you just need to repoint it to the modified copy as you leave.</p>

<p>Edit: other comments relative to modifying a list while you iterate it are not accurate, as you are not modifying the list you are iterating on, you are modifying the "copy" of the list.  While others have offered good suggestions on improving the conciseness of the method, your original method was perfectly valid with the above tweaks. </p>

<p>Edit2: volcano's 'comment' relative to the global is correct, the global statement should be added inside the def to perform it this way. reference volcano's answer for the best approach, but I'll leave this around for the discussion point. </p>

python python-2.7