How does str.startswith really work?

Viewed 4292

I've been playing for a bit with startswith() and I've discovered something interesting:

>>> tup = ('1', '2', '3')
>>> lis = ['1', '2', '3', '4']
>>> '1'.startswith(tup)
True
>>> '1'.startswith(lis)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: startswith first arg must be str or a tuple of str, not list

Now, the error is obvious and casting the list into a tuple will work just fine as it did in the first place:

>>> '1'.startswith(tuple(lis))
True

Now, my question is: why the first argument must be str or a tuple of str prefixes, but not a list of str prefixes?

AFAIK, the Python code for startswith() might look like this:

def startswith(src, prefix):
    return src[:len(prefix)] == prefix

But that just confuses me more, because even with it in mind, it still shouldn't make any difference whether is a list or tuple. What am I missing ?

3 Answers
Related