Python Forum

Full Version: I don't understand why this doesn't work
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
(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.
Thank you, may I ask what could be a good solution for this to work as I intended?
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)
(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.