Search code examples
pythonfilterstartswith

why is name.startswith('a') returning True on the name 'barry'?


I am trying to learn how to use the .startswith() method and also the filter() function. For some reason I am not getting the result I expected. I don't know if I am misunderstanding 'startswith' or 'filter'.

here is the code i used

names = ['aaron','anthony','tom','henry','barry']
def start_a(names):
    for name in names:
        if name.startswith('a'):
            return True
            
            
        
print(list(filter(start_a, names)))

i was expecting to get ['aaron', 'anthony'] however i got ['aaron', 'anthony', 'barry']

does anyone know where i went wrong? thanks


Solution

  • start_a() is looping over the characters in the name, because it just receives one list element as its parameter. So it's actually checking whether the name contains a, not whether it starts with a.

    filter() does the looping over the list for you, you don't need another loop in the function.

    def start_a(name):
        return name.startswith('a')