[Tutor] Another assert() question

Danny Yoo dyoo at cs.wpi.edu
Sat Jul 12 22:24:04 CEST 2008

> In my code I have
> assert(len(list(set(colors_used_this_cycle))) ==
> len(colors_used_this_cycle), "A color has been used twice!")
> But it doesn't work. Cases where a color has been used more than once go
> right through it

Let's try a simple example.

Go back to the structure of an assert statement.

    assert condition[, expression]   ## template

Let's think of a very simple condition.  How about False?  Let's
replace the "condition" part above with False, and not provide an
expression yet.

>>> assert False
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

Ok, good.  Now let's try to also fill in an expression.  Let's have
the expression be "I expected this".  So we look back at our template:

    assert condition[, expression]   ## template

We're going to substitute False as our condition, and "I expected
this" as our expression.

>>> assert False, "I expected this."
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: I expected this.

That also seems to work.

If the expression gets a little more complicated, the form of the
assertion statement still stays the same.  Let's say that we're
checking to see that the square root of -1 is 1j.  The condition we're
checking is:

    (cmath.sqrt(-1) == 1j)

and the expression is "Bad math."  Then:

>>> import cmath
>>> assert (cmath.sqrt(-1) == 1j), "Bad math"

We didn't see anything, so the assertion's condition is true.  Let's
artificially induce it to fail.

>>> assert (cmath.sqrt(1) == 1j), "Bad math"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: Bad math

Can you go through a similar exercise with your own condition and
expression?  Isolate the condition part of what you want to test, the
expression part that you want to show, and then just plug directly
into the assert template.

(The problem here is that you've run across one of the edge cases in
Python's syntax involving parenthesized expressions.  Anyone who says
that you can disregard parentheses in Python is not telling the

More information about the Tutor mailing list