Reputation: 139
I want to write a function that will remove a certain integer from a list. Both of the values are input. For example, removeValues([1, 2, 3], 3)
would return the list [1, 2]
:
def removeValues(aList, n):
newList = []
if n in aList:
aList.remove(n)
newList.append(aList)
else:
return False
I am not sure if .remove
is the right way to go.
Upvotes: 0
Views: 458
Reputation: 418
A function that will remove all occurrences of a specific value from a list could be written like so:
>>> def removeAll(list, value):
... while value in list:
... list.remove(value)
...
>>> a = [1,2,3,3,4]
>>> removeAll(a, 3)
>>> print( a )
[1,2,4]
Upvotes: 0
Reputation: 6633
Use a list comprehension
def removeValues(aList, n):
return [ i for i in aList if i != n ]
Upvotes: 2
Reputation: 1575
list(filter(lambda x : x != 3, [1,2,3]))
Use filter, Filter takes a function reference and list of elements. the function is written to accept a list element and return true or false based on the desired predicate like x != 3
. for every element the function checks the predicate and only if the condition return True the element is included in the output list.
As said in the comments, a simple remove on the list will do the job.
Upvotes: 0