A few weeks ago, I ran into an interesting problem on a Python Flask project. An array of strings (in this case, email accounts) needed to be sorted - and if any of the strings contained specific words (like “test”, for example), the associated user accounts needed to be modified slightly to indicate test user status.
There are a number of different approaches you can take to accomplish this, but Python includes a really great function to help smooth this process out - and it’s dead simple.
Let’s start by making a test list:
Notice we have a good mix - email addresses, URLs, and just plain strings. We want to find any and all occurances of the specific strings in our email address data set and mark the user associated as a tester.
It’s as simple as that. What
any() does is it checks if any of the words in our test data ‘email’ match any words defined in our
test_list. If so, we set
test_user to true.
For more reading on the
any() (and its cousin,
all()) function in Python, check out this excellent write-up that goes into more detail.