'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?
Solution 1:[1]
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.
Solution 2:[2]
>>> a = [0, 1]
>>> b = [0, 1, 2, 3]
>>> a[:min(len(a), len(b))] == b[:min(len(a), len(b))]
True
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tomerikoo |
| Solution 2 | Woodford |
