if statement on lenght of a list

Chris Rebert clp2 at rebertia.com
Tue May 17 14:31:19 EDT 2011


On Tue, May 17, 2011 at 11:02 AM, Joe Leonardo
<joe.leonardo at datalogix.com> wrote:
>
> Hey all,
>
> Totally baffled by this…maybe I need a nap. Writing a small function to reject input that is not a list of 19 fields.
>
> def breakLine(value):
>     if value.__class__() != [] and value.__len__() != 19:
>         print 'You must pass a list that contains 19 fields.'
>     else:
>         print 'YAY!'
>
> If I pass:
> breakLine([])
>
> I get:
> YAY!
>
> I expect:
> You must pass a list that contains 19 fields.

Your test should use `or` as opposed to `and`. Since you're indeed
passing in a list, the first part of your condition is False; since
you used `and`, this makes the entire condition False. Therefore, the
else clause ("YAY!") gets executed.

Also, your test is written quite strangely. One would more normally
and straightforwardly write it as:
    if not isinstance(value, list) or len(value) != 19:

Cheers,
Chris
--
http://rebertia.com



More information about the Python-list mailing list