Python, if any() else in list comprehension

This one took me about 20-30 minutes to figure out today and required stringing together some SO answers, so I’m putting what I learned here for future reference.
The scenario: searching if 1 of multiple strings exists in a longer string.  In this case, some possible Twitter clients in the source field of a tweet object.

The answer:

these = ['Twitter Web Client', 'Hootsuite']
desktop = [1 if any(x in item for x in these) else 0 for item in data['source']]

The loop version of the code is

these = ['Twitter Web Client', 'Hootsuite']
ugh = []
for item in data['source']:
	if any(x in item for x in these):
		ugh.append(1)
	else:
		ugh.append(0)

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.