Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #5594 > unrolled thread

Re: if statement on lenght of a list

Started byEthan Furman <ethan@stoneleaf.us>
First post2011-05-17 12:07 -0700
Last post2011-05-17 12:07 -0700
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: if statement on lenght of a list Ethan Furman <ethan@stoneleaf.us> - 2011-05-17 12:07 -0700

#5594 — Re: if statement on lenght of a list

FromEthan Furman <ethan@stoneleaf.us>
Date2011-05-17 12:07 -0700
SubjectRe: if statement on lenght of a list
Message-ID<mailman.1694.1305658534.9059.python-list@python.org>
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!'

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web