0

python list's remove method has some issues. I have attached the code below. The code does not remove all elements with length less than 3

result=[['10'], ['5'], ['6'], ['12'], ['9'], ['10'], ['5', '9', '10'], 
['5', '10'], ['13'], ['9', '10'], ['1']]

for i in result:
    if len(i)<=2:
        result.remove(i)
print (result)

The result prints as [['5'], ['12'], ['10'], ['5', '9', '10'], ['12']] Any help is really welcomed and appreciated

General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • 1
    You shouldn't remove items from a list while iterating it. Instead, build a new list with the items you want to keep. – roganjosh Jun 02 '18 at 11:07
  • 1
    Deleting from a list while iterating over it is like sawing off the branch you’re sitting on. – zvone Jun 02 '18 at 11:12

1 Answers1

2

The problem is, that you are manipulating the list while iterating over it. You better create a filtered copy of the result list:

result=[['10'], ['5'], ['6'], ['12'], ['9'], ['10'], ['5', '9', '10'], ['5', '10'], ['13'], ['9', '10'], ['1']]

filtered_result = []

for i in result:
    if len(i)>2:
        filtered_result.append(i)

print(filtered_result)

Or for example using filter:

result = filter(lambda x: len(x)>2, result)

You could also use list comprehension:

result = [x for x in result if len(x)>2]
miindlek
  • 3,523
  • 14
  • 25