Skip to content
Advertisement

How to retrieve partial matches from a list of strings

For approaches to retrieving partial matches in a numeric list, go to:


But if you’re looking for how to retrieve partial matches for a list of strings, you’ll find the best approaches concisely explained in the answer below.

SO: Python list lookup with partial match shows how to return a bool, if a list contains an element that partially matches (e.g. begins, ends, or contains) a certain string. But how can you return the element itself, instead of True or False

Example:

JavaScript

Here, the approach in the linked question will return True using:

JavaScript

So how can you return the element 'threes' instead?

Advertisement

Answer

  • startswith and in, return a Boolean.
  • The in operator is a test of membership.
  • This can be performed with a list-comprehension or filter.
  • Using a list-comprehension, with in, is the fastest implementation tested.
  • If case is not an issue, consider mapping all the words to lowercase.
    • l = list(map(str.lower, l)).
  • Tested with python 3.11.0

filter:

  • Using filter creates a filter object, so list() is used to show all the matching values in a list.
JavaScript

list-comprehension

JavaScript

Which implementation is faster?

  • Tested in Jupyter Lab using the words corpus from nltk v3.7, which has 236736 words
  • Words with 'three'
    • ['three', 'threefold', 'threefolded', 'threefoldedness', 'threefoldly', 'threefoldness', 'threeling', 'threeness', 'threepence', 'threepenny', 'threepennyworth', 'threescore', 'threesome']
JavaScript

%timeit results

JavaScript
Advertisement