Search code examples
pythonpython-3.xlistreturn

Returning empty list


Hi I have problem with my program, I try to check which letters in alphabet doesn't appear in list, unluckily it returns empty list I don't know why

I tried many ways but it still doesn't work...

import string
def get_missing_letters(s):
    missing =[]
    alphabet = list(string.ascii_lowercase)
    s = list(s)
    for letter in s:
        if letter not in alphabet:
            missing.append(letter)
        return missing
print(get_missing_letters("abcdefgpqrstuvwxyz"))

Solution

  • You have two issues, the return happens after the first iteration and you are actually checking if the letters in your string exists in ascii_lowercase instead of the opposite

    def get_missing_letters(s):
        missing = []
        s = list(s)
        for letter in list(string.ascii_lowercase):
            if letter not in s:
                missing.append(letter)
        return missing
    
    
    print(get_missing_letters("abcdefgpqrstuvwxyz"))
    # ['h', 'i', 'j', 'k', 'l', 'm', 'n', 'o']
    

    Another way to find the diff is to use set

    def get_missing_letters(s):
        return set(string.ascii_lowercase).difference(s)
        # or
        return set(string.ascii_lowercase) - set(s)
    
    print(get_missing_letters("abcdefgpqrstuvwxyz"))
    # {'j', 'n', 'k', 'l', 'i', 'm', 'o', 'h'}
    

    You can sort it if the order is important to you

    def get_missing_letters(s):
        missing = set(string.ascii_lowercase).difference(s)
        return sorted(missing)
    
    
    print(get_missing_letters("abcdefgpqrstuvwxyz"))
    # ['h', 'i', 'j', 'k', 'l', 'm', 'n', 'o']