Home > database >  issue iterating a python string list
issue iterating a python string list

Time:02-13

Hello I'm getting an issue while I'm trying to remove every len of string in the list that is mod by 2

def remove_even_length(l):
for i in l:
    if  len(i) %2==0:
        if i in l:

            l.remove(i)


return l

wordlist = ["be", "is", "not", "or", "question", "the", "to"] print(remove_even_length(wordlist))

what is happening is when it goes inside the list it skips ,[is , question] which both are mod 2 I don't know why it doesn't check the len of these 2 strings.

CodePudding user response:

Might be a problem resulting from the fact that you are iterating over the list while changing it.

Try creating a new list and returning it:

def remove_even_length(old_list):
    new_list = []
    for i in old_list:
        if len(i) % 2 != 0:
            new_list.append(i)
    return new_list


wordlist = ["be", "is", "not", "or", "question", "the", "to"]
wordlist_without_even = remove_even_length(wordlist)
print(wordlist_without_even)

Or just use a List Comprehension:

wordlist = ["be", "is", "not", "or", "question", "the", "to"]
wordlist_without_even = list([word for word in wordlist if len(word) % 2 != 0])
print(wordlist_without_even)

CodePudding user response:

You're operating on the list as you're iterating through it. Try creating a separate results list, and pushing the values that do/don't fit your criteria to this new list. I think you'll find your results then.

CodePudding user response:

It happens because you are removing elements while iterating which changes the length of list while looping. You can use the following code to remove the elements based on a condition in one line.

def remove_even_length(l):
    l1 = [x for x in l if len(x) % 2]


    return l1

CodePudding user response:

I figure it out I must remove every even element backwards.

def remove_even_length(l):
for i in l[::-1]:
    if not (len(i) %2==1):
        l.remove(i)
return l
wordlist = ["be", "is", "not", "or", "question", "the", "to"]
print(remove_even_length(wordlist))
  • Related