Python中判断元素是否在列表的逻辑错误解析及正确实现
Hey there! Let's break down why that unexpected test output is happening, and go over the right way to write this condition.
The issue comes down to operator precedence and how Python evaluates boolean expressions with or. Let's unpack the problematic condition step by step:
if('a' or 'b' or 'c' in ['notin']): print('test')
- First, Python evaluates the highest-precedence operator first:
in. Soc in ['notin']runs first, which returnsFalse(since'c'isn't in the list). - Now your condition simplifies to
'a' or 'b' or False. - The
oroperator uses "short-circuit evaluation": it returns the first truthy value it encounters. A non-empty string like'a'is consideredTruein a boolean context. So Python immediately returnsTruefor the entire expression, making theifcondition pass—hence thetestprintout.
This is not checking if any of 'a', 'b', or 'c' are in the list—it's just checking if 'a' is truthy (which it always is), ignoring the rest of the expression.
To actually check if any of the values exist in the list, you need to pair each value with the in operator, then combine them with or:
if 'a' in ['notin'] or 'b' in ['notin'] or 'c' in ['notin']: print('test')
This will only print test if at least one of 'a', 'b', or 'c' is present in the list—exactly what you intended.
any() Solution is Great! I love that you used any() for your fix—it's the most Pythonic approach, especially when you have a long list of values to check. A small optimization: using a set instead of a list for your target values will make the in checks faster (O(1) vs O(n) time complexity), which matters if you're working with large datasets:
target_values = {'a', 'b', 'c'} # Sets have faster lookup if any(t in target_values for t in ['a', 'b']): print('in list') if not any(t in target_values for t in ['d', 'e']): print('not in list')
内容的提问来源于stack exchange,提问作者blue-sky

