Winkleson here looking for some help on a very simplistic question… I’m pretty out of it at the moment but I’d like to figure out what I am doing wrong with this problem 🙂 Of course anyother methods to solve the problem would be excellent! Thankyou in advance!
Question:
Remove Item
Create a function that takes a list and a value and returns a list
with all occurrences of the given value removed.
Pretty simple right? My head is going to hurt when I facepalm… Anyways here are the calls.
Calls:
>>> remove(['a','b','c','d','e'],'e')
['a','b','c','d']
>>> remove([4,2,7,6,7,8,3,1,3,5],3)
[4,2,7,6,7,8,1,5]
>>> remove([4,4,4,4],4)
[]
>>> remove([1,2,3,4,5,6,7],'hi')
[1,2,3,4,5,6,7]
My Code:
def remove(l,o): #l is list, o is object
for i in l:
if i == o: #If the current item is the object to be removed...
l.remove(o) #Remove the object
return l #Finally return the list.
So… Here’s the issue:
Call: remove([4,4,4,4],4)
Supposed to return:[]
What is returned: [4, 4]
Correct: False
So… If anyone out there knows what’s going on it would be great if you were to share your knowledge! Furthermore any other methods of solving would be great as well. Hints would also be great if they aren’t too vague. Anyways, Thanks in advance! – Winkleson
P.s. I’m still a beginner programmer so please don’t be too hard on me 😛 Thanks alot!
Your problem is that you’re trying to iterate over the list at the same time you’re changing the list. In the first iteration:
Python looks at l[0], and deletes it.
Now the list is:
Since it just did l[0], Python now wants to look at l[1]. But since the list has changed, the value that used to be at l[1] is at l[0] instead, and gets skipped.
One option is to build a new list as you go:
Since this is a common sort of operation, Python lets you do the same thing with “list comprehensions”, which are very handy:
(As a side note, it’s generally a bad idea to use 1-letter variable names. It’s an especially bad idea with “o” and “l”, which can easily be mistaken for “0” and “1”, respectively.)