Python Forum
I don't understand why this doesn't work - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: I don't understand why this doesn't work (/thread-23285.html)



I don't understand why this doesn't work - sandeen - Dec-19-2019

can someone please explain to me why the third item in the list is not removed?

def alist(x):
    for i in x:
        if len(i) != 4:
            x.remove(i)
    return x


test = alist(['Yoda', '123', 'whyisthisnotremoved', 'testing', 'test', '', '1234'])
print(test)
Thanks

oh.. as I am looking at it:
Is it because when the first item is removed the index changes and moves the 3d item to index [1] in this case, while the for loop continues on with index 2 etc.. ?

I guess that might be it now that I think about it, but I would still like to hear the explanation from someone more experienced that my self. Because I could not figure it out otherwise.

If thats the case what would be a good solution for this to work as I intended?


RE: I don't understand why this doesn't work - buran - Dec-19-2019

(Dec-19-2019, 07:10 PM)sandeen Wrote: Is it because when the first item is removed the index changes and moves the 3d item to index [1] in this case, while the for loop continues on with index 2 etc.. ?
that's correct.


RE: I don't understand why this doesn't work - sandeen - Dec-19-2019

Thank you, may I ask what could be a good solution for this to work as I intended?


RE: I don't understand why this doesn't work - buran - Dec-19-2019

def alist(x):
    return [item for item in x if len(item) == 4]

def alist2(x):
    return list(filter(lambda item: len(item) == 4, x))
 
test = alist(['Yoda', '123', 'whyisthisnotremoved', 'testing', 'test', '', '1234'])
test2 = alist2(['Yoda', '123', 'whyisthisnotremoved', 'testing', 'test', '', '1234'])
print(test)
print(test2)



RE: I don't understand why this doesn't work - sandeen - Dec-19-2019

(Dec-19-2019, 07:36 PM)buran Wrote:
def alist(x): return [item for item in x if len(item) == 4] def alist2(x): return list(filter(lambda item: len(item) == 4, x)) test = alist(['Yoda', '123', 'whyisthisnotremoved', 'testing', 'test', '', '1234']) test2 = alist2(['Yoda', '123', 'whyisthisnotremoved', 'testing', 'test', '', '1234']) print(test) print(test2)

Thanks again, simpel and easy to read.