Anxenon
Anxenon

Reputation: 21

How to determine if an item in a list begins with a certain character? (Python)

I'm trying to iterate through a list in python, and determine if any of the items in the list begins with the character "a". However, my code seems to only check the first item in the list and doesn't iterate through the rest.

def isA(myList):
for i in range(len(myList)):
    if myList[i][0] == "a":
        print "True"
        return True
    else:
        print "False"
        return False

For example isA(["acorn", "baseball"]) would return True, but isA(["baseball", "acorn"] returns False, when it should return True because there is an item in the list that begins with a.

Upvotes: 1

Views: 80

Answers (2)

zondo
zondo

Reputation: 20336

Just use the any() function:

def isA(mylist):
    if any(l.startswith("a") for l in mylist):
        print "True"
        return True
    else:
        print "False"
        return False

Upvotes: 1

Kevin
Kevin

Reputation: 76194

You have a return in the if block, and a return in the else block. So no matter how the condition evaluates, you will absolutely hit a return and the function will immediately terminate, having iterated no more than once.

If you want to check whether any item begins with "a", don't return as soon as you find an item that doesn't start with "a". Move that return to the end of the function.

def isA(myList):
    for i in range(len(myList)):
        if myList[i][0] == "a":
            return True
    return False

Alternatively, skip writing the function altogether and use the built-in function any.

>>> any(s.startswith("a") for s in ["baseball", "acorn"])
True

Upvotes: 5

Related Questions