-4

In python, how can I remove all occurrences of an integer from a list. For example:

list_a = [5, 20, 15, 10, 55, 30, 65]
list_a.METHOD(5)
print(list_a)
[20, 10, 30]

Essentially, the method removes anything that contains a 5. Not specifically multiples of 5, given that 10 and 20 do not contain a 5. Thanks.

  • 1
    Possible duplicate of [Remove all occurrences of a value from a Python list](http://stackoverflow.com/questions/1157106/remove-all-occurrences-of-a-value-from-a-python-list) – utsav_deep Feb 08 '17 at 18:30
  • Oh, it's not a dupe of that, per se. – kojiro Feb 08 '17 at 18:54

3 Answers3

1
list_a = [5, 20, 15, 10, 55, 30, 65]
list_a = [x for x in list_a if "5" not in str(x)]
print(list_a)
[20, 10, 30]
yedpodtrzitko
  • 9,035
  • 2
  • 40
  • 42
0

This is one way:

[x for x in list_a if str(x).find('5') < 0]

That's a list comprehension that converts each number to a string and then searches the string for the character 5. find returns -1 if not found so we keep only things where the 5 wasn't found.

Oliver Dain
  • 9,617
  • 3
  • 35
  • 48
0

You can use filter and lambda.

filter(lambda x:"5" not in str(x) , [5, 20, 15, 10, 55, 30, 65])
Bipul Jain
  • 4,523
  • 3
  • 23
  • 26