user16519472
user16519472

Reputation:

How to check if one list starts with another?

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

Answers (3)

ThePyGuy
ThePyGuy

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

javier__
javier__

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

Woodford
Woodford

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

Related Questions