Home > Back-end >  Removing even length strings but returning only one of them
Removing even length strings but returning only one of them

Time:04-24

def remove_even_length(thisList):
    for i in range(0,len(thisList)):
        splittoString = thisList[i].split(' ')
        
        for word in splittoString:
            if not len(word)%2 ==0:
                print(word)

This code prints what I want.

def remove_even_length(thisList):
    for i in range(0,len(thisList)):
        splittoString = thisList[i].split(' ')
        
        for word in splittoString:
            if not len(word)%2 ==0:
                return(word)

But does only return first odd number not the rest

I used this as a example List

['even', 'odd', 'ev', 'o']

Why can't I get whole word as a return but only first odd number? How can I have it return me every odd word?

CodePudding user response:

As soon as you call return in a function, the function exits.

Change that to this

def remove_even_length(thisList):
    array = []
    for i in range(0,len(thisList)):
        splittoString = thisList[i].split(' ')

        for word in splittoString:
            if not len(word)%2 ==0:
                array.append(word)

    return array

Update:

To change thisList and not create a new list use this

thisList = ["hello", "world", "abcd"]
thisList = remove_even_length(thisList)

Update 2

This will modify thisList instead of creating a new list

def remove_even_length(thisList):
    for i in range(0,len(thisList)):
        splittoString = thisList[i].split(' ')

        for word in splittoString:
            if len(word)%2 ==0:
                thisList.remove(word)

    #uncomment next line if you want to return the list from this function
    #return thisList

CodePudding user response:

Your return statement is called the first time you get a match.

Put all your matches in a list and then return the list once all the words have been processed.

  • Related