Reputation: 2127
Is there an equivalent of starts with for lists in python ?
I would like to know if a list a starts with a list b. like
len(a) >= len(b) and a[:len(b)] == b ?
Upvotes: 3
Views: 1372
Reputation: 101072
For large lists, this will be more efficient:
from itertools import izip
...
result = all(x==y for (x, y) in izip(a, b))
For small lists, your code is fine. The length check can be omitted, as DavidK said, but it would not make a big difference.
PS: No, there's no build-in to check if a list starts with another list, but as you already know, it's trivial to write such a function yourself.
Upvotes: 0
Reputation: 354
it does not get much simpler than what you have (and the check on the lengths is not even needed)... for an overview of more extended/elegant options for finding sublists in lists, you can check out the main answer to this post : elegant find sub-list in list
Upvotes: -1
Reputation: 2564
You can just write a[:len(b)] == b
if len(b) > len(a), no error will be raised.
Upvotes: 6