Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - check if a letter is in a list

If a letter (string) is in a list, find_letter(['o', ['hello', 'c', 'bye']), return True, if not return False.

def find_letter(lst):

    lst=['o','hello', 1]
    n='o'

    if not lst:          
        return 0

    elif lst[0] == n:
        return True

    elif find_letter(lst[0:]):
        return True

    else: 
        return False


print(find_letter(lst))

It does return 'True', but I am not sure if this is the right way to do this. Maybe there's a better way? In the second elif-statement, is python going through all the elements in the list if the first one doesn't contain the letter? The function must be recursive.

like image 220
raspberrysupreme Avatar asked Oct 14 '14 07:10

raspberrysupreme


2 Answers

I think the most pythonic approach would be to use

def find_letter(letter, lst):
    return any(letter in word for word in lst)

The beauty of this is that it iterates over lst and returns as soon as one of the words in that list contains letter. Also, it doesn't need to recurse.

This returns False instead of 0 if lst is empty, though (unlike your program) but since False evaluates to 0 anyway (and vice versa), that's not really an issue.

like image 163
Tim Pietzcker Avatar answered Oct 07 '22 06:10

Tim Pietzcker


Since you need a recursive version:

Short version

def find_letter(let, lst):
    return (lst or False) and \
           ((isinstance(lst[0], str) and let in lst[0]) or find_letter(let, lst[1:]))

More explicit version

def find_letter(let, lst):
    if lst:
        e = lst[0]
        return (isinstance(e, str) and let in e) or find_letter(let, lst[1:])
    return False

Even more explicit version

def find_letter(let, lst):
    if lst:
        e = lst[0]
        if isinstance(e, str) and let in e:
            return True
        return find_letter(let, lst[1:])
    return False

Note that I leave out a couple of else: because they are not necessary after a return statement. If you don't want to test for a letter in a string, but just for equality, replace let in ... by let == ....

like image 33
uselpa Avatar answered Oct 07 '22 07:10

uselpa