Python List Comprehensions Help

That made me feel like you're not sure what your goal is. Sorry if I was rude, didn't mean to be.

One deals with words in strings, the other deals with characters.
Also, I find that using all() and any() makes it clear what is expected.

Actually your way was totally valid. I just find the logic kind of backwards - I'd tend to check if my string is in the list of strings to exclude, instead of checking if the strings to exclude match my string.

edit:
Here's a version that will handle characters, words, numbers, pretty much anything you throw at it, as long as values are in lists:

def is_this_list_valid(values, required_values=None, forbidden_values=None):
	req_check = True
	if required_values is not None:
		req_check = all(v in values for v in required_values)
	excl_check = True
	if forbidden_values is not None:
		excl_check = not any(v in forbidden_values for v in values)
	return req_check and excl_check


req = [42, 'foo', {'baz': "BAZ"}]
excl = ["bar", 21, 'a']

tests = [
	['bla', 42, 'b', 'foo', {'baz': "BAZ"}],
	['42', 'foo', 'baz'],
	[42, 'foo', 21]
]

for t in tests:
	print(is_this_list_valid(t, req, excl))
# > True
# > False
# > False

Might be simpler to just pass empty lists on call instead of using None as default, but... blah.

2 Likes