assert type([]) == type(())

V

VanceE

Just curious.

type([]) == type(())
is False as expected

and

assert type([]) == type(())
throws an AssertionError as expected.

However the following is not an error

for x in []:
assert type(x) == type(())

I expected an AssertionError but get no errors at all.
Any explaination?

BTW I'm using Python2.5 and tried
type(None) == type(())
which is False as expected.

TIA
 
J

Josh Holland

for x in []:
assert type(x) == type(())

I expected an AssertionError but get no errors at all.
Any explaination?

That loop never runs. It immediately raises a StopIteration and the body
is never executed.
cf.

for x in []:
print "In loop body"

You won't see anything printed.

OTOH, look at this one:

for x in [[]]: # a list containing an empty list
assert type(x) == type(())

That will raise the AssertionError as expected.
 
W

Wojciech Mu³a

VanceE said:
for x in []:
assert type(x) == type(())

I expected an AssertionError but get no errors at all.
Any explaination?

[] is an empty sequence, so your loop executes exactly 0 times. :)

for x in [None]:
assert ...

w.
 
T

Tim Chase

However the following is not an error
for x in []:
assert type(x) == type(())

I expected an AssertionError but get no errors at all.
Any explaination?


number_of_times_through_the_loop = 0
for x in []:
assert type(x) == type(())
number_of_times_through_the_loop += 1

print number_of_times_through_the_loop

make sense? :)

-tkc
 
J

Jan Kaliszewski

However the following is not an error
for x in []:
assert type(x) == type(())

Trying to iterate over an empty sequence or iterator causes
0 (zero) steps of iteration -- so above assert statement is
never run.

Cheers,
*j
 
M

Mel

VanceE said:
Just curious.

type([]) == type(())
is False as expected

and

assert type([]) == type(())
throws an AssertionError as expected.

However the following is not an error

for x in []:
assert type(x) == type(())

I expected an AssertionError but get no errors at all.
Any explaination?

Others have said what happens. Bit of a mind bender -- here's the smallest
change to do what you expected:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
.... assert type(x) == type (())
....
Traceback (most recent call last):


Because of the comma, this creates a tuple containing the empty list, and
iterates over the tuple.

Mel.
 
V

VanceE

A big Thank You to all for the answer (and the hints).
That sure explains a lot.

Again, Thank you very much.

Cheers,
Vance
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,183
Messages
2,570,966
Members
47,513
Latest member
JeremyLabo

Latest Threads

Top