Search code examples
pythonlistfor-loopnested-lists

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


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


Solution

  • 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]