if statement on lenght of a list

Ethan Furman ethan at stoneleaf.us
Tue May 17 15:07:44 EDT 2011


Joe Leonardo wrote:
> 
> 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!

Change your 'and' to an 'or'.

Also, change your 'value.__len__()' to 'len(value)'.

Finally, if you absolutely don't want any iterable that might work (such 
as a tuple), change 'value.__class__() != []' to either 'type(value) != 
list' or, if subclasses are okay (and they probably should be) 'not 
isinstance(value, list)'.

Incorporating these suggestions looks like this:

def breakLine(value):
     if not isinstance(value, list) or len(value) != 19:
         print 'You must pass a list that contains 19 fields.'
     else:
         print 'YAY!'





More information about the Python-list mailing list