16

For the following list:

test_list = ['one', 'two','threefour']

How would I find out if an item starts with 'three' or ends with 'four' ?

For example, instead of testing membership like this:

two in test_list

I want to test it like this:

startswith('three') in test_list.

How would I accomplish this?

David Kehoe
  • 161
  • 1
  • 1
  • 3

4 Answers4

13

You can use any():

any(s.startswith('three') for s in test_list)
sth
  • 211,504
  • 50
  • 270
  • 362
  • what is the time complexity of this lookup? would it still be asymptotically equivalent to a set lookup? – Hamed Sep 02 '21 at 19:30
9

You could use one of these:

>>> [e for e in test_list if e.startswith('three') or e.endswith('four')]
['threefour']
>>> any(e for e in test_list if e.startswith('three') or e.endswith('four'))
True
samplebias
  • 35,728
  • 6
  • 100
  • 102
3

http://www.faqs.org/docs/diveintopython/regression_filter.html should help.

test_list = ['one', 'two','threefour']

def filtah(x):
  return x.startswith('three') or x.endswith('four')

newlist = filter(filtah, test_list)
sleeplessnerd
  • 20,433
  • 1
  • 24
  • 29
0

If you're looking for a way to use that in a conditional you could to this:

if [s for s in test_list if s.startswith('three')]:
  # something here for when an element exists that starts with 'three'.

Be aware that this is an O(n) search - it won't short circuit if it finds a matching element as the first entry or anything along those lines.

g.d.d.c
  • 44,141
  • 8
  • 97
  • 109