Witnesses and Counterexamples
Witnesses and counterexamples. In the examples you’ve seen so far, the assignment expression operator does essentially the same job as the assignment operator in your old code. You’ve seen how to simplify code, and now you’ll learn about a different type of use case that’s made possible by this new operator. In this section, you’ll learn how you can find witnesses when calling
any() by using a clever trick that isn’t possible without using the walrus operator.
A witness in this context is an element that satisfies the check and causes
any() to return
True. By applying similar logic, you’ll also learn how you can find counterexamples when working with
all(). A counterexample in this context is an element that doesn’t satisfy the check and causes
all() to return
In each of these cases,
all() give you a plain
False answer. What if you’re also interested in seeing an example or a counterexample of the city names? It could be nice to see what’s causing the
Well, no, because
"Oslo" doesn’t. In other words, you want a witness or a counterexample to justify the answer. Capturing a witness to an
any() expression has not been intuitive in earlier versions of Python.
Here, you first capture all city names that start with
"H". Then, if there’s at least one such city name, you print out the first city name starting with
"H". Note that here you’re not actually using
any(), even though you’re doing a similar operation with a list comprehension. By using the walrus operator, you can find witnesses directly in your
They only check as many items as necessary to determine the result. If you want to check whether all city names start with the letter
"H", then you can look for a counterexample by replacing
all() and updating the
print() functions to report the first item that doesn’t pass the check.
Combining the walrus operator and
any() works by iteratively assigning each item that’s being checked to
witness. However, only the last such item survives and shows which item was last checked by
Become a Member to join the conversation.