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


Groups > comp.lang.python > #5594

Re: if statement on lenght of a list

Date 2011-05-17 12:07 -0700
From Ethan Furman <ethan@stoneleaf.us>
Subject Re: if statement on lenght of a list
References <8F54BE3F56F7A64ABDC3A8164CC83FFA0AB4A096A9@VA3DIAXVS331.RED001.local>
Newsgroups comp.lang.python
Message-ID <mailman.1694.1305658534.9059.python-list@python.org> (permalink)

Show all headers | View raw


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!'

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

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

csiph-web