0

I want to use forloop to delete some element that meets the conditions.

name_list = ["Win-0.3.4-x86_64", "CentOS7.1"]

for name in name_list:
    if "snapshot" not in name:
        name_list.remove(name)

print name_list  # there print ['CentOS7.1']

But in the end, it do not delete all the elements that meet the condition.

maer
  • 156
  • 3
  • 15
  • Because, you modify the list in place, so the size shrinks. Don't do that. – cs95 Oct 13 '17 at 03:25
  • A normal iteration won't be correct if you are modifying what you are iterating. – Spencer Wieczorek Oct 13 '17 at 03:25
  • Removing items from a list that you're iterating over is like sawing off a tree branch that you're sitting on. If you saw on the wrong side Bad Things happen. ;) You _can_ safely remove items from a list if you iterate over it in reverse, but generally it's simpler to just iterate normally and build a new list. – PM 2Ring Oct 13 '17 at 04:13

1 Answers1

0

You can not forloop the list, and modify the list's element in place, the iterating will not normal execute.

You can copy the list to a new list, then forloop the new list, and remove the origin list.

You try to use bellow code:

import copy

name_list = ["Win-0.3.4-x86_64", "CentOS7.1"]

name_list_cp = copy.copy(name_list)

for name in name_list_cp:
    if "snapshot" not in name:
        name_list.remove(name)


print name_list

In the end, will print a empty list [].

aircraft
  • 25,146
  • 28
  • 91
  • 166