Reputation: 1660
What is the easiest (most pythonic way) to check, if the beginning of the list are exactly the elements of another list? Consider the following examples:
li = [1,4,5,3,2,8]
#Should return true
startsWithSublist(li, [1,4,5])
#Should return false
startsWithSublist(list2, [1,4,3])
#Should also return false, although it is contained in the list
startsWithSublist(list2, [4,5,3])
Sure I could iterate over the lists, but I guess there is an easier way. Both list will never contain the same elements twice, and the second list will always be shorter or equal long to the first list. Length of the list to match is variable.
How to do this in Python?
Upvotes: 14
Views: 7042
Reputation: 180391
You can do it using all
without slicing and creating another list:
def startsWithSublist(l,sub):
return len(sub) <= l and all(l[i] == ele for i,ele in enumerate(sub))
It will short circuit if you find non-matching elements or return True if all elements are the same, you can also use itertools.izip
:
from itertools import izip
def startsWithSublist(l,sub):
return len(sub) <= l and all(a==b for a,b in izip(l,sub))
Upvotes: 3
Reputation: 2710
Use list slicing:
>>> li = [1,4,5,3,2,8]
>>> sublist = [1,4,5]
>>> li[:len(sublist)] == sublist
True
Upvotes: 25