0

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.

4 Answers 4

2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.