Python implements an example of deleting elements in a list that meet certain criteria

  • 2020-06-03 07:17:18
  • OfStack

This article is an example of an Python implementation that deletes elements from a list that meet 1 criteria. To share for your reference, specific as follows:

Deletes an element from the list that satisfies a condition of 1.

For example, delete an element of length 0 in a list, or delete an element that is a multiple of 2 and 3 in a list.

Those of you who have done high-level programming may think, "It's easy," but you can do it this way:


for i in listObj:
  if(...):
    listObj.remove(i)

Take a look at a small example and the results:


a = [1, 2, 3, 12, 12, 5, 6, 8, 9]
for i in a:
    if i % 2 == 0 and i % 3 == 0:
      a.remove(i)
print(a)

Operation results:


E:\Program\Python>d.py
[1, 2, 3, 12, 5, 8, 9]

See? 12 has not been deleted!! (This is a very error-prone area for Python list operations)

There are many workarounds to achieve your desired goals. For example:


a = [1, 2, 3, 12, 12, 5, 6, 8, 9]
b = a[:]
for i in a:
    if i % 2 == 0 and i % 3 == 0:
      b.remove(i)
a = b
print(a)

Operation results:


E:\Program\Python>d.py
[1, 2, 3, 5, 8, 9]

Look at that. Now we're there. As you can see from the above code, we build List b, copy all the elements in list a, delete the elements in b by traversing a, and finally point a to b.

I've also found another way, which I think is pretty good -- the list derivation


a = ['what', '', '', 'some', '', 'time']
a = [i for i in a if len(i) > 0]
print(a)
b = [1, 2, 3, 12, 12, 5, 6, 8, 9]
b = [i for i in b if not(i % 3 == 0 and i % 2 == 0)]
print(b)

Operation results:


E:\Program\Python>d.py
['what', 'some', 'time']
[1, 2, 3, 5, 8, 9]

Which do you think is the better way to write it? From the point of view of performance, the efficiency may not be too good, but from the point of view of concise writing, I prefer the latter!

More Python related content interested readers to view this site project: "Python list (list) skills summary", "Python coding skills summary", "Python data structure and algorithm tutorial", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article has been helpful for Python programming.


Related articles: