Alex Kamphuis Alex Kamphuis - 9 months ago 87
Python Question

find lists that start with items from another list

I have a manifold of lists containing integers. I store them in a list (a list of lists) that I call biglist.

Then I have a second list, eg [1, 2].

Now I want to find all lists out of the big_list that start with the same items as the small list. The lists I want to find must have at least all the items from the second list.

I was thinking this could be done recursively, and came up with this working example:

def find_lists_starting_with(start, biglist, depth=0):
if not biglist: # biglist is empty
return biglist

new_big_list = []
# try:
for smallist in biglist:
if smallist[depth] == start[depth]:
if not len(start) > len(smallist):

new_big_list = find_lists_starting_with(start,
return new_big_list
except IndexError:
return biglist

biglist = [[1,2,3], [2,3,4], [1,3,5], [1, 2], [1]]
start = [1, 2]

print(find_lists_starting_with(start, biglist))

However I am not very satisfied with the code example.

Do you have suggestions as how to improve:
- understandability of the code
- efficiency

Answer Source

You can try it via an iterator, like so:

[x for x in big_list if x[:len(start_list)] == start_list]