15

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?

2 Answers 2

25

Use list slicing:

>>> li = [1,4,5,3,2,8]
>>> sublist = [1,4,5]
>>> li[:len(sublist)] == sublist
True
0
3

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))
5
  • 1
    Note that your index-based approach will throw if the sublist is longer than the sequence and matches up to the length, e.g. startsWithSublist([1,2,3],[1,2,3,4]), and your second will return True in that case (even though it probably shouldn't). (And yes, I know the OP ruled that case out, but still, it's a disadvantage slicing doesn't have.)
    – DSM
    Aug 21, 2015 at 21:14
  • @DSM, added len(sub) <= l to handle that case. Aug 21, 2015 at 21:16
  • Thank you very much for your response. I like the simplicity of the above answer, but also see the advantages of your solution. However, memory utilization and performance are not important in this case, as the lists are rather small (<= 5 entries), and I prefer the simple solution.
    – Daniel
    Aug 21, 2015 at 21:23
  • 1
    @waza-ari, yep, the slicing is the simplest approach, if you had large data this would be a more memory efficient approach. Aug 21, 2015 at 21:24
  • Is that supposed to be len(sub) <= len(l)? Nov 12, 2018 at 23:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.