Reputation:
If I have two lists in Python, [0, 1]
and [0, 1, 2, 3]
, how do I check if the first list starts with the second?
I know how to do this with strings, just use the startswith
method. But apparently you can't do that for lists.
Is there a one-liner that does what I described?
Upvotes: 0
Views: 254
Reputation: 18416
Just iterate them parallelly and check that the corresponding values are equal. You can create a generator expression for the equality iterating using zip
, along with all
:
>>> a = [0, 1]
>>> b = [0, 1, 2, 3]
>>> all(i==j for i,j in zip(a,b))
True
This works because zip
stops when the shortest iterable is exhausted.
Upvotes: 1
Reputation: 22
I think this is what you meant
if the list x starts with the list y
>>> x[0:len(y)] == y
True
>>> x
[0, 1, 2, 3]
>>> y
[0, 1]
Upvotes: 0
Reputation: 4449
>>> a = [0, 1]
>>> b = [0, 1, 2, 3]
>>> a[:min(len(a), len(b))] == b[:min(len(a), len(b))]
True
Upvotes: 0