Given a large string, finding the length of the first longest even length sub-string I am writing a function where I can take a string as input, and then find the even number of substrings. The final result is the first longest even length string is returned by the function.

For example:

Input -> It is a pleasant day today

Output -> pleasant

For example:

Input -> It is a day today

Output-> It

(Since there are two sub-strings of the same even length, returning the first longest even length string is enough.)

If there are no such even length strings then, the function should return 00.

import sys


def longestEvenWord(sentence):
    list1 = sentence.split()

    for x in list1[:]:
        # just removing all the odd length words from
        # the list. Then the list will contain only
        # even words
        if (len(x) % 2 != 0):
            list1.remove(x)
    #after removing the odd length numbers, we will have only even and find the
    #longest word and return that.
    return max(list1, key=len)


if __name__ == '__main__':
    result = longestEvenWord(" qqqqqqqqq It is a day today qqqqqqqqq")
    print(result)
Firstly, "sub-string" is different than "word". I think "word" is more appropriate in this situation. (A substring can contain non-alphabetical characters).

import sys


You never use this. Get rid of it.

list1 = sentence.split()


This assignment is not terribly necessary.

Your algorithm can be simplified considerably. I think this should be left as an exercise, but here are some things you shouldn't have to do in the new algorithm:


Don't make a copy of the list.
Have some sort of best variable and best_count integer that stores the longest even word found and the length of that word.
After looping through the sentnce, return best.


Using this algorithm you only hit each word once instead of going through the even words again as you do in your algorithm.

The PEP8 style guide states that Python functions use snake_case instead of camelCase so: longestEvenWord -&gt; longest_even_word.