0

I intended to remove the elements with '0' in the end or only with '0', and my codes are:

s = ['a0', 'b0', '0', 'c', 'd']
for x in s:
    if x[-1] == '0' or x == '0':
        s.remove(x)

s #result
['b0', 'c', 'd']

When I debug, I found that after 'a0' is removed, the s becomes ['b0', '0', 'c', 'd'], then as I thought, x will be 'b0', but it turn out to be '0', so it skipps the 'b0', I am wondering the reason behind that and how to fix it?

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
user5802211
  • 197
  • 1
  • 9

1 Answers1

4

Don't modify a list while you are iterating over it (more information here).

Instead, try filtering the list all at once:

s = [x for x in s if x[-1] != '0']
Community
  • 1
  • 1
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272