Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether a list starts with the elements of another list

Tags:

python

list

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?

like image 895
waza-ari Avatar asked Aug 21 '15 21:08

waza-ari


People also ask

How do you check if a list contains elements of another list?

To check if a list contains any elements of another list: Use a generator expression to iterate over the list. Check if any elements in the first list are contained in the second list. The any() method will return True if the list contains any elements of the other list.

How do I check if an item is in a list B list in Python?

Given two lists A and B, write a Python program to Check if list A is contained in list B without breaking A's order. A more efficient approach is to use List comprehension. We first initialize 'n' with length of A. Now use a for loop till len(B)-n and check in each iteration if A == B[i:i+n] or not.


2 Answers

Use list slicing:

>>> li = [1,4,5,3,2,8]
>>> sublist = [1,4,5]
>>> li[:len(sublist)] == sublist
True
like image 171
Josh Kupershmidt Avatar answered Sep 17 '22 15:09

Josh Kupershmidt


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))
like image 34
Padraic Cunningham Avatar answered Sep 17 '22 15:09

Padraic Cunningham