2

Is there an equivalent of starts with for lists in python ?

I would like to know if a list a starts with a list b. like

len(a) >= len(b) and a[:len(b)] == b ?
Bhavesh Odedra
  • 10,990
  • 12
  • 33
  • 58
ElefEnt
  • 2,027
  • 1
  • 16
  • 20
  • 1
    What's wrong with that? There is not so much to optimize. – Christian Tapia May 28 '14 at 07:33
  • @Christian, it would not be wrong to do the same with strings as well, but there is an API – ElefEnt May 28 '14 at 07:35
  • I don't think there's anything way simpler than that. – cnluzon May 28 '14 at 07:36
  • @ElefEnt, I think you can do the same with strings too, and pretty much any iterable – cnluzon May 28 '14 at 07:37
  • And how do you think the methods in an API are implemented? – Christian Tapia May 28 '14 at 07:37
  • @cnluzon I know I was just answering to the comment above, saying that though it's already simple there is still something better, for strings – ElefEnt May 28 '14 at 07:38
  • I see what you mean now. I somehow did not get it exactly like that when I read it. I do not know for sure if such functionality does not exist. However, I find your solution already simple enough not to need it. But I guess that's also a matter of taste. – cnluzon May 28 '14 at 07:42

3 Answers3

5

You can just write a[:len(b)] == b

if len(b) > len(a), no error will be raised.

DavidK
  • 2,495
  • 3
  • 23
  • 38
  • you mean len(b) <= len(a)? – cnluzon May 28 '14 at 07:38
  • No error will be raised in any situation. Slicing past the length of the list will not fail. – Tim May 28 '14 at 07:39
  • it's true, but the condition should be met in order for it to work properly – cnluzon May 28 '14 at 07:40
  • 2
    No, it shouldn't be. It will work for `len(a) < len(b)`, `len(a) == len(b)`, and `len(a) > len(b)`. The former will always be `false`, but the code will work perfectly fine. – Tim May 28 '14 at 07:41
  • @Tim: `False`, not `false`. This is Python, not Java (or any other language where boolean constants start with a lowercase letter.) – ArtOfWarfare Apr 29 '15 at 01:43
0

For large lists, this will be more efficient:

from itertools import izip
...
result = all(x==y for (x, y) in izip(a, b))

For small lists, your code is fine. The length check can be omitted, as DavidK said, but it would not make a big difference.

PS: No, there's no build-in to check if a list starts with another list, but as you already know, it's trivial to write such a function yourself.

Community
  • 1
  • 1
sloth
  • 99,095
  • 21
  • 171
  • 219
-1

it does not get much simpler than what you have (and the check on the lengths is not even needed)... for an overview of more extended/elegant options for finding sublists in lists, you can check out the main answer to this post : elegant find sub-list in list

Community
  • 1
  • 1
MultiVAC
  • 354
  • 1
  • 10