checking if a list is empty

2011-05-05 Thread Jabba Laci
Hi,

If I want to check if a list is empty, which is the more pythonic way?

li = []

(1) if len(li) == 0:
...
or
(2) if not li:
...

Thanks,

Laszlo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-06 Thread Chris Rebert
On Thu, May 5, 2011 at 11:36 PM, Jabba Laci  wrote:
> Hi,
>
> If I want to check if a list is empty, which is the more pythonic way?

Option (2), IMO.

> li = []
>
> (1) if len(li) == 0:
> ...

FYI, also equivalent:
if not len(li):
...

> or
> (2) if not li:

Cheers,
Chris
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-06 Thread Richard Thomas
On May 6, 7:36 am, Jabba Laci  wrote:
> Hi,
>
> If I want to check if a list is empty, which is the more pythonic way?
>
> li = []
>
> (1) if len(li) == 0:
> ...
> or
> (2) if not li:
> ...
>
> Thanks,
>
> Laszlo

I prefer (1), it feels more explicit about what I'm testing. The fact
that empty sequences evaluate as false feels like a bit of a quirk to
me. Actually the fact that 0 evaluates as false feels like a bit of a
quirk to me, I more of a "use booleans in boolean contexts" kind of
programmer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-06 Thread James Mills
On Fri, May 6, 2011 at 4:36 PM, Jabba Laci  wrote:
> If I want to check if a list is empty, which is the more pythonic way?

[...]

> (2) if not li:

This is fine.

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-06 Thread Terry Reedy

On 5/6/2011 7:34 AM, James Mills wrote:

On Fri, May 6, 2011 at 4:36 PM, Jabba Laci  wrote:

If I want to check if a list is empty, which is the more pythonic way?


[...]


(2) if not li:


This is fine.


This is the intended way. Anything in addition is extra noise and wasted 
calculation. In other words, let Python do the boilerplate work for you.


--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-06 Thread harrismh777

Terry Reedy wrote:

(2) if not li:


This is fine.


This is the intended way. Anything in addition is extra noise and wasted
calculation. In other words, let Python do the boilerplate work for you.


   I agree, but I don't like it.

... if not li  says nothing about what li is supposed to 'be' and 
implies in any case that li does not exist, or worse is some kind of 
boolean.


   li is in fact an empty list [] and will identify as such, and of 
course (as a list object) has all of the attributes and methods of a list...


   Why not have a list method that makes this more explicit:


   if not li.emptylist()

   if not li.empty([])

  there might be others...



kind regards,
m harris


--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-06 Thread Eric Snow
On Fri, May 6, 2011 at 1:31 PM, Terry Reedy  wrote:

> On 5/6/2011 7:34 AM, James Mills wrote:
>
>> On Fri, May 6, 2011 at 4:36 PM, Jabba Laci  wrote:
>>
>>> If I want to check if a list is empty, which is the more pythonic way?
>>>
>>
>> [...]
>>
>>  (2) if not li:
>>>
>>
>> This is fine.
>>
>
> This is the intended way. Anything in addition is extra noise and wasted
> calculation. In other words, let Python do the boilerplate work for you.
>
>
That works for lists, but for a class that implements a list-like interface,
subclassing list or not, it will not always work the way you want.  The
language reference indicates that, for the implicit cast to a bool, __bool__
is checked on the object, then __len__, and then it defaults to True [1].
 So the above only works the way you expect if __len__ is the normal length
for a list and __bool__ is not defined.

I ran into this once when I had a class that defined __len__ but wanted the
object to cast to True no matter what.  For my case I chose to redefine
__bool__.

So it seems like this boils down to what you want to know.  Is the list
empty (length 0) or is the boolean version false?  Again, for lists these
are the same.  For list-like classes they are not necessarily the same.

Incidently, you can also check "if li == []:".  This will let the __eq__
operator jump in.

-eric

[1] http://docs.python.org/dev/py3k/reference/datamodel.html#object.__bool__

-- 
> Terry Jan Reedy
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-06 Thread Adam Tauno Williams
On Fri, 2011-05-06 at 14:49 -0500, harrismh777 wrote:
> Terry Reedy wrote:
> >>> (2) if not li:
> >> This is fine.
> > This is the intended way. Anything in addition is extra noise and wasted
> > calculation. In other words, let Python do the boilerplate work for you.
> I agree, but I don't like it.

+1  This is the Python reality-distortion-field at work.

Motto#1: Python is all about readability!
Motto#2: Crytic code is awesome if it is Pythoncally cryptic!

I'd never accept code like "if not x" as an empty test.

> ... if not li  says nothing about what li is supposed to 'be' and 
> implies in any case that li does not exist, or worse is some kind of 
> boolean.
> li is in fact an empty list [] and will identify as such, and of 
> course (as a list object) has all of the attributes and methods of a list...
> Why not have a list method that makes this more explicit:
> if not li.emptylist()
> if not li.empty([])
> there might be others...

Good luck.  Just code -
  # You can immediately tell what this is meant to do!
  if len(x) == 0:  
- and ignore the Pythonistas [they're nuts;  that x.count() doesn't work
is amazingly stupid].

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-06 Thread Chris Rebert
On Fri, May 6, 2011 at 1:05 PM, Adam Tauno Williams
 wrote:

> - and ignore the Pythonistas [they're nuts;  that x.count() doesn't work
> is amazingly stupid].

Eh? It works fine. [5, 2, 2, 1, 2].count(2) == 3. If you mean you want
len(x) to be spelled x.count(), that's equally stupid; `count` would
be a lousy name (people would confuse it with what the current
.count() does). `length` or `size` would make much more sense.

Cheers,
Chris
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-06 Thread scattered
On May 6, 2:36 am, Jabba Laci  wrote:
> Hi,
>
> If I want to check if a list is empty, which is the more pythonic way?
>
> li = []
>
> (1) if len(li) == 0:
> ...
> or
> (2) if not li:
> ...
>
> Thanks,
>
> Laszlo

is there any problem with

(3) if li == []:

?

Seems to work when I test it and seems to clearly test what you are
trying to test. The only problem might be if in some contexts == has
the semantics of checking for object identity.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-06 Thread Raymond Hettinger
On May 5, 11:36 pm, Jabba Laci  wrote:
> Hi,
>
> If I want to check if a list is empty, which is the more pythonic way?
>
> li = []
>
> (1) if len(li) == 0:
> ...
> or
> (2) if not li:

The Python core developers use the second form.
See http://www.python.org/dev/peps/pep-0008/
for the official recommendation.


Raymond

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-06 Thread Philip Semanchuk

On May 6, 2011, at 5:57 PM, scattered wrote:

> On May 6, 2:36 am, Jabba Laci  wrote:
>> Hi,
>> 
>> If I want to check if a list is empty, which is the more pythonic way?
>> 
>> li = []
>> 
>> (1) if len(li) == 0:
>> ...
>> or
>> (2) if not li:
>> ...
>> 
>> Thanks,
>> 
>> Laszlo
> 
> is there any problem with
> 
> (3) if li == []:
> 
> ?

What if it's not a list but a tuple or a numpy array? Often I just want to 
iterate through an element's items and I don't care if it's a list, set, etc. 
For instance, given this function definition --

def print_items(an_iterable):
if not an_iterable:
print "The iterable is empty"
else:
for item in an_iterable:
print item

I get the output I want with all of these calls:
print_items( list() )
print_items( tuple() )
print_items( set() )
print_items( numpy.array([]) )

Given this slightly different definition, only the  first call gives me the 
output I expect: 

def print_items(an_iterable):
if an_iterable == []:
print "The iterable is empty"
else:
for item in an_iterable:
print item


I find I use the the former style ("if not an_iterable") almost exclusively.


bye
Philip




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-06 Thread Ian Kelly
On Fri, May 6, 2011 at 4:21 PM, Philip Semanchuk  wrote:
> What if it's not a list but a tuple or a numpy array? Often I just want to 
> iterate through an element's items and I don't care if it's a list, set, etc. 
> For instance, given this function definition --
>
> def print_items(an_iterable):
>    if not an_iterable:
>        print "The iterable is empty"
>    else:
>        for item in an_iterable:
>            print item
>
> I get the output I want with all of these calls:
> print_items( list() )
> print_items( tuple() )
> print_items( set() )
> print_items( numpy.array([]) )

But sadly it fails on iterators:
print_items(xrange(0))
print_items(-x for x in [])
print_items({}.iteritems())
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-06 Thread Jon Clements
On May 7, 12:51 am, Ian Kelly  wrote:
> On Fri, May 6, 2011 at 4:21 PM, Philip Semanchuk  wrote:
> > What if it's not a list but a tuple or a numpy array? Often I just want to 
> > iterate through an element's items and I don't care if it's a list, set, 
> > etc. For instance, given this function definition --
>
> > def print_items(an_iterable):
> >    if not an_iterable:
> >        print "The iterable is empty"
> >    else:
> >        for item in an_iterable:
> >            print item
>
> > I get the output I want with all of these calls:
> > print_items( list() )
> > print_items( tuple() )
> > print_items( set() )
> > print_items( numpy.array([]) )
>
> But sadly it fails on iterators:
> print_items(xrange(0))
> print_items(-x for x in [])
> print_items({}.iteritems())

My stab:

from itertools import chain

def print_it(iterable):
it = iter(iterable)
try:
head = next(it)
except StopIteration:
print 'Empty'
return
for el in chain( (head,), it ):
print el

Not sure if I'm truly happy with that though.

Jon
Jon.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-06 Thread Chris Angelico
On Sat, May 7, 2011 at 6:05 AM, Adam Tauno Williams
 wrote:
> On Fri, 2011-05-06 at 14:49 -0500, harrismh777 wrote:
>> Terry Reedy wrote:
>> >>> (2) if not li:
>> >> This is fine.
>> > This is the intended way. Anything in addition is extra noise and wasted
>> > calculation. In other words, let Python do the boilerplate work for you.
>>     I agree, but I don't like it.
>
> +1  This is the Python reality-distortion-field at work.
>
> Motto#1: Python is all about readability!
> Motto#2: Crytic code is awesome if it is Pythoncally cryptic!

As a C and C++ programmer, I probably shouldn't offer an opinion, but
it is quite normal in C++ to compare objects for truth/falseness - for
instance, stream objects return false on error/eof, so you can
efficiently code a loop with "while (infile) {...}". Not to mention
that the nullness of a C string (a PSZ) is quite happily and safely
tested by seeing if the pointer is true (non-null) or false (null).

That said, though, readability is a relative thing. A construct is
transparently obvious if it does something in the exact same way that
it's always been done, no matter how obscure it was the first time.
Why is it, for instance, that putting two short strokes perpendicular
to one another indicates addition? Yet if you see the construct "x +
y", you know exactly what it means - it's readable, it's not cryptic
at all. People assume and expect that this compact syntax will be
available, and object heavily to such notation as "add(x,y)" which
says exactly what it does.

if not li:

is perfectly readable; you just need a comprehension of what truth
means for a list.

Chris Angelico
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-06 Thread Steven D'Aprano
On Fri, 06 May 2011 16:05:09 -0400, Adam Tauno Williams wrote:

> I'd never accept code like "if not x" as an empty test.

So much the worse for you then.

The point of the "if x" idiom is that it is a polymorphic test which is 
independent of the type. It works with any non-broken object[1], no 
matter what x is, since it allows x to decide for itself whether it is 
empty or not.

Of course, you can write your own polymorphic test:


try:
flag = len(x) == 0
except TypeError:
# This *should* succeed, for anything not broken. If not, we can't
# recover, so just let the exception propagate.
flag = bool(x)
# Hilariously, bool(x) may also try len(x) == 0... oh well.
if flag:
...

Congratulations! You've now found a way to write "if x:" in five lines, 
53 characters (plus whitespace and comments) and an extraneous variable 
polluting the namespace. If you're being paid per line of code, this is a 
good win.

Of course, sometimes you don't want polymorphism (or at least, not too 
much polymorphism). Sometimes I'll write "if x == 0" or similar if I want 
to emphasize that x is a special case unrelated to the truth/falseness of 
x. But that's quite rare. Normally I trust x to decide for itself whether 
it is empty or not.





[1] Arguably with the exception of iterables. But then the len(x) test 
doesn't work for them either.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-06 Thread Steven D'Aprano
On Fri, 06 May 2011 14:57:21 -0700, scattered wrote:

> is there any problem with
> 
> (3) if li == []:
> 
> ?
> 
> Seems to work when I test it and seems to clearly test what you are
> trying to test. The only problem might be if in some contexts == has the
> semantics of checking for object identity.

Yes, if li == [] works too. But how do you know li is a list and not some 
other sequence type?

The advantage of the "if x" test is that it is independent of the type of 
x.

-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-07 Thread Steven D'Aprano
On Fri, 06 May 2011 14:49:24 -0500, harrismh777 wrote:

> Terry Reedy wrote:
 (2) if not li:
>>>
>>> This is fine.
>>
>> This is the intended way. Anything in addition is extra noise and
>> wasted calculation. In other words, let Python do the boilerplate work
>> for you.
> 
> I agree, but I don't like it.
> 
> ... if not li  says nothing about what li is supposed to 'be' 

Yes, and? Neither does:

isempty(li)  # li could be anything that polymorphic isempty can deal with
li.isempty()  # li could be anything with a "isempty" method
len(li) == 0  # li could be anything with a length (list, dict, set, ...)


That's duck-typing for you, and it is generally a strength rather than a 
weakness. For those times when it is a weakness, that's where we have 
naming conventions, type-testing, and (in some languages) static types.


> and implies in any case that li does not exist

It does nothing of the sort. If li doesn't exist, you get a NameError.


> or worse is some kind of boolean.

Only if you're still thinking in some language that isn't Python.

Boolean tests in Python are polymorphic. bool() exists mainly to provide 
a canonical representation of true and false values, not because you are 
limited to using booleans in truth-testing. Far from it: it is often very 
useful to do something like this:

settings = local_settings or global_settings or builtin_settings

where the first non-empty *_settings wins.


> li is in fact an empty list [] and will identify as such, and of
> course (as a list object) has all of the attributes and methods of a
> list...
> 
> Why not have a list method that makes this more explicit:

For the same reason that we don't have an int method that makes zero 
testing more explicit:

n = 0
n.iszero()  # returns True


Because sometimes you can have too much explicitness.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-07 Thread harrismh777

Steven D'Aprano wrote:

... if not li  says nothing about what li is supposed to 'be'

Yes, and? Neither does:

isempty(li)  # li could be anything that polymorphic isempty can deal with
li.isempty()  # li could be anything with a "isempty" method
len(li) == 0  # li could be anything with a length (list, dict, set, ...)


 Sure.


That's duck-typing for you, and it is generally a strength rather than a
weakness. For those times when it is a weakness, that's where we have
naming conventions, type-testing, and (in some languages) static types.


 I can fix almost anything with duck-type...:)


>  and implies in any case that li does not exist

It does nothing of the sort. If li doesn't exist, you get a NameError.


 That was the point.   'not' implies something that is not logical; 
which is irony extreme since 'not' is typically considered a logical 
operator.   What does it mean to say  not ?  Well, apparently 
it means the list is 'empty'... but why should it mean that? Why not 
have it mean the list has been reversed in place?  Why not have it mean 
that the list isn't homogeneous?  Why not have it mean that its not 
mutable?  I could think of more... Why should 'not' mean 'empty'?



>  or worse is some kind of boolean.

Only if you're still thinking in some language that isn't Python.


   Which most of us are... hate to remind you...   Python is the new 
kid on the block, and most of us are coming at this from multiple 
filters in comp sci experience.  Its just the truth.



>   Why not have a list method that makes this more explicit:

For the same reason that we don't have an int method that makes zero
testing more explicit:



Because sometimes you can have too much explicitness.


True.


kind regards,

m harris


--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-07 Thread Ethan Furman

harrismh777 wrote:

Steven D'Aprano wrote:

>>>  attribution lost wrote:

>  and implies in any case that li does not exist

It does nothing of the sort. If li doesn't exist, you get a NameError.


 That was the point.   'not' implies something that is not logical; 
which is irony extreme since 'not' is typically considered a logical 
operator.   What does it mean to say  not ?  Well, apparently 
it means the list is 'empty'... but why should it mean that? Why not 
have it mean the list has been reversed in place?  Why not have it mean 
that the list isn't homogeneous?  Why not have it mean that its not 
mutable?  I could think of more... Why should 'not' mean 'empty'?


Because this is Python, and in Python that's what it means.




>  or worse is some kind of boolean.

Only if you're still thinking in some language that isn't Python.


   Which most of us are... hate to remind you...   Python is the new kid 
on the block, and most of us are coming at this from multiple filters in 
comp sci experience.  Its just the truth.


And your point would be?

If you're going to use a language, and use it well, you have to learn 
how that language works.


~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-08 Thread Steven D'Aprano
On Sat, 07 May 2011 22:50:55 -0500, harrismh777 wrote:

> Steven D'Aprano wrote:

>>> >  and implies in any case that li does not exist
>> It does nothing of the sort. If li doesn't exist, you get a NameError.
> 
>   That was the point.   'not' implies something that is not logical;

I'm afraid that makes no sense to me. How does "does not exist" imply 
something not logical? In what way is "this is not my house" implying 
something not logical?


> which is irony extreme since 'not' is typically considered a logical
> operator.

Because "not" is typically used as a logical operator.

In English, it negates a word or statement:

"the cat is not on the mat" --> "the cat is on the mat" is false.

As an operator, "not" negates a true value to a false value. In 
mathematical Boolean algebra, there only is one true value and one false 
value, conventionally called True/False or 1/0. In non-Boolean algebras, 
you can define other values. In three-value logic, the negation of True/
False/Maybe is usually False/True/Maybe. In fuzzy logic, the logic values 
are the uncountable infinity (that's a technical term, not hyperbole) of 
real numbers between 0 and 1.

Python uses a boolean algebra where there are many ways of spelling the 
true and false values. The "not" operator returns the canonical bool 
values:

not  returns False
not  returns True

Take note of the distinction between lower-case true/false, which are 
adjectives, and True/False, which are objects of class bool.

This is not unique to Python. I understand the practice of allowing any 
value to be used in boolean expressions comes from Lisp in 1958, which 
makes it practically antediluvian.

Lisp uses the empty list and the special atom NIL as false values, any 
other s-expression is true. Scheme is different: it defines a special 
false atom, and empty lists are considered true. In Ruby, only the false 
object and the null object are considered false. In Forth, any non-zero 
word is true. In Javascript, the empty string, null, undefined, NaN, +0, 
-0, and false are all considered false.



> What does it mean to say  not ?  Well, apparently
> it means the list is 'empty'... but why should it mean that? 

Because that is the definition chosen by the language designers. It is 
based on the fact that distinguishing between "something" and "nothing" 
is useful, common, fundamental, and applies to nearly all data types.


> Why not
> have it mean the list has been reversed in place?  Why not have it mean
> that the list isn't homogeneous?  Why not have it mean that its not
> mutable?  I could think of more... 

Because those tests are not fundamental tests that deserve to be elevated 
to a language design feature, any more than we need a built-in function 
to add 27 and three quarters to the argument.


> Why should 'not' mean 'empty'?

Because the test of "is this nothing, or something?" is a common, useful 
test:

0 (nothing) vs 1, 2, 3, ... (something)
empty list versus non-empty list
empty dict versus non-empty dict
empty set versus non-empty set
empty string versus non-empty string
no search results returned versus some search results returned
no network connection available versus some network connection available
no food in the cupboard versus food in the cupboard

This is a fundamental distinction which is very useful in practice. 


>>> >  or worse is some kind of boolean.
>> Only if you're still thinking in some language that isn't Python.
> 
> Which most of us are... hate to remind you...   

Time to stop then. This is Python, not whatever language you're thinking 
in. Don't force language A into the conceptual pigeonholes of language B. 
To be effective in a programming language, you need to understand how 
that language works, and not see everything filtered through the 
conceptual framework of another language.

Bringing the viewpoints of other languages is a good thing. Python 
borrows concepts from many languages (sometimes what it borrows is the 
idea of "that's not how to do it"). And many idioms do cross language 
boundaries. But in general, it pays to think, and code, in the 
appropriate style for whatever language you are writing in. And 
certainly, you should not argue that a language feature is invalid or 
wrong merely because that's not how another language does it.

Or, to put it another way:

http://dirtsimple.org/2004/12/python-is-not-java.html
http://dirtsimple.org/2004/12/java-is-not-python-either.html



> Python is the new kid on the block, 

Nonsense. Python is 20 years old (1991), which makes it older than:

Java, PHP, Ruby (1995)
Javascript (1996)
C# (2000)
Visual Basic .Net (2001)

to say nothing of dozens of other languages.


> and most of us are coming at this from multiple
> filters in comp sci experience.  Its just the truth.

There's nothing wrong with having experience in many languages. That's a 
good thing.




-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-08 Thread Jussi Piitulainen
Steven D'Aprano writes:

> Lisp uses the empty list and the special atom NIL as false values,
> any other s-expression is true. Scheme is different: it defines a
> special false atom, and empty lists are considered true. In Ruby,

I'll inject a pedantic note: there is only one false value in both
Lisp (which now is mostly Common Lisp) and Scheme.

The empty list () and the symbol NIL in Lisp are one value, not two
values. The first Google hit (for me, just now) explains it the way I
understand it: .
(Common Lisp The Language, 2nd edition. Odd place to find that book.
It predates the formal standard, but then I think this particular
feature of the language is, indeed, as old as you say, and unlikely to
have changed.)

Scheme was the same. Then for a time it was not specified whether the
empty list was distinct from the false value or the symbol nil -
people disagreed and implementations were allowed to differ - until
the three were definitely separated.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-08 Thread Terry Reedy

On 5/8/2011 10:07 AM, Steven D'Aprano wrote:


Because the test of "is this nothing, or something?" is a common, useful
test:


Because inductive algorithms commonly branch on 'input is something' 
(not done, change args toward 'nothing'and recurse or iterate) versus 
'input is nothing (done, return base expression).



0 (nothing) vs 1, 2, 3, ... (something)
empty list versus non-empty list
empty dict versus non-empty dict
empty set versus non-empty set
empty string versus non-empty string


and non-inductive algorithms also branch on the same question.


no search results returned versus some search results returned
no network connection available versus some network connection available
no food in the cupboard versus food in the cupboard

This is a fundamental distinction which is very useful in practice.


Definitely. Python commonly hides the distinction inside of iterators 
called by for statememts, but StopIteration is understood as 'collection 
is empty'. An I suspect something vs. nothing is also the most common 
overt condition in if and while statements.


--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-08 Thread Dan Stromberg
On Sun, May 8, 2011 at 3:41 PM, Terry Reedy  wrote:

> On 5/8/2011 10:07 AM, Steven D'Aprano wrote:
>
>  Because the test of "is this nothing, or something?" is a common, useful
>> test:
>>
>
> Because inductive algorithms commonly branch on 'input is something' (not
> done, change args toward 'nothing'and recurse or iterate) versus 'input is
> nothing (done, return base expression).
>

Just what is an inductive algorithm?

I'm familiar with inductive reasoning and inductive proofs, but there
doesn't seem to be much on the 'net defining inductive algorithms.  There
are some papers that reference the topic, but few seem to spend much time on
defining it.  They seem to have to do with A.I. knowledge acquisition -
perhaps it's an algorithm that reasons from a bunch of factlets to create a
general rule?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-08 Thread Michael Torrie
On 05/08/2011 05:36 PM, Dan Stromberg wrote:
> Just what is an inductive algorithm?

>From what I can remember, it's just an implementation of a proof
essentially.  Any algorithm that can be inductively proven can be
implemented with recursion and specific base cases.  In other words you
program just like you'd do the proof.  First you deal with the base
cases and then you can call yourself for F(n) and F(n-1).  The inductive
proof provides the pattern for the code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-08 Thread harrismh777

Steven D'Aprano wrote:

which is irony extreme since 'not' is typically considered a logical
>  operator.

Because "not" is typically used as a logical operator.

In English, it negates a word or statement:

"the cat is not on the mat" -->  "the cat is on the mat" is false.


   Your pedantic bogus cat analogy talks past my point entirely, as 
well as making you look silly... if you would stop being pedantic long 
enough to think about what I'm saying you might come to some 
understanding...


... yes, 'not' is a logical negation. Why would you waste time with a 
pedantic explanation of 'not' ?   Wait--- its a rhetorical question...



   Why should the negation of a list imply that the list empty?  ... 
nor any other abstract condition which is not well suited to 'not' ? 
(forget python for a moment... then move on to my argument...)


   What made the python development team (or individual) decide that 
the logical construct   'not list'   would return True if the list is 
empty?   To say that "This is the way we do it in Python because Python 
does it this way"---  goes beyond pedantic becoming circular and redundant.


   On the other hand, if you were to tell me *why* you think that the 
logical construct 'not list' should be logically True when the list is 
empty--- when clearly negating a list would not necessarily mean to make 
the list empty (including destroying it)... then you might be seeing my 
point.


   Here's the bottom line you missed...

... although syntactically correct, the following test is not a logical 
construct that makes sense (except for the syntactically initiated):


if not list  <=  this makes no logical sense...

... to test for an empty list . . .

... although, it is legal syntax.   :-}


   I know that is the way Python does it... I've been coding it that 
way for a long time...  but that doesn't answer my concern



   To say this another way, IMHO,

if not list


...  should return True only if 'list' is bound to NULL, or if 
the name 'list' would throw a name exception...


...  and, Python should have an explicit way of testing for an 
empty list that is clear, concise, and easy to understand even for the 
relatively new Python programmer.  This is not intended to generate 
counter argument, its just my feedback on a language construct that I 
find to be inconsistent logically. ... Please, no pedantic discourse 
explaining why I'm wrong... just put in into a PEP and move on.  :)






kind regards,
m harris




--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-08 Thread harrismh777

Steven D'Aprano wrote:

Python is the new kid on the block,

Nonsense. Python is 20 years old (1991), which makes it older than:

Java, PHP, Ruby (1995)
Javascript (1996)
C# (2000)
Visual Basic .Net (2001)


   Python is the new kid on the block.


   ... not chronologically perhaps, but measured in terms of acceptance 
and widespread use it is only really now coming into its own. It usually 
takes an advance in technology about 20 - 25 years to catch on... and 
Python has finally arrived IMHO.


   As an example of this... in many default setups in linux distros 
today Python is now the default 'Programming' environment. This was not 
true in 1991, nor was it true in 2001... in fact, this has not been true 
until the past couple of years. Python is catching on in the community 
at large... not just specialized development shops. As I've given my 
opinion before on this list, Python is finally becoming the New BASIC 
for 'people'.


   Python is also the new kid on the block in educational settings. 
Haskell and Erlang have dominated for some time now (in fact, many 
colleges and universities have focused beginning classes on pure 
functional programming)... and before that Pascal and Lisp... and in 
limited ways C  or C++  ./  Python is moving into that arena lately.


   For me personally, the environment provided by TCL/Tk was the way 
for many years... TCL was the glue, Tk was the graphics, and 'C' was the 
engine  (it all works together seamlessly with great performance and 
minimal lines of coding).  Python takes it up a notch; big time. 
Because, as you've pointed out, less has to be written in 'C'.  Almost 
all of the app can be written in Python, with only one (or three) mods 
written in 'C'... frankly, for most scripting, the whole thing can be 
written in Python. But *this* is a relatively *new* discovery for much 
of the community at large. (I'm not talking here about Google, nor YouTube).


   Linux is in this same boat... Linux is twenty years old; however, 
Linux has not enjoyed wide-spread use on the Desktop (until this year, 
and part of last) and has only enjoyed wide-spread use on servers over 
the past ten years. Linux is now coming into its own, and when 
everything is said and done and all the dust settles history is going to 
find Windows as a minor footnote in personal computing (I'm talking 100 
years from now).


   Linux is the new kid on the block, twenty years old and kicking 
it...   Python is the new kid on the block... twenty years old and 
kicking it  many of us are catching up with the new trend; however, 
we will be evaluating the new trends through historic filters. This 
cannot be avoided--- for linux, nor for python.



kind regards,
m harris


--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-08 Thread Ian Kelly
On Sun, May 8, 2011 at 9:33 PM, harrismh777  wrote:
>   Why should the negation of a list imply that the list empty?  ... nor any
> other abstract condition which is not well suited to 'not' ? (forget python
> for a moment... then move on to my argument...)
>
>   What made the python development team (or individual) decide that the
> logical construct   'not list'   would return True if the list is empty?
> To say that "This is the way we do it in Python because Python does it this
> way"---  goes beyond pedantic becoming circular and redundant.
>
>   On the other hand, if you were to tell me *why* you think that the logical
> construct 'not list' should be logically True when the list is empty--- when
> clearly negating a list would not necessarily mean to make the list empty
> (including destroying it)... then you might be seeing my point.

"bool(list)" describes whether the list contains something.  "Not"
being a logical operator, it stands to reason that "not list" should
mean the same thing as "not bool(list)".  Anything else would be
surprising and pointlessly convoluted.  If "not list" bothers you,
then I would suggest that your problem is actually with "bool(list)".

>        ...  should return True only if 'list' is bound to NULL, or if the
> name 'list' would throw a name exception...

Why?  Should "not False" return True only if "False" is bound to NULL
(whatever you mean by that), or if the name "False" would throw a name
exception?

>        ...  and, Python should have an explicit way of testing for an empty
> list that is clear, concise, and easy to understand even for the relatively
> new Python programmer.  This is not intended to generate counter argument,
> its just my feedback on a language construct that I find to be inconsistent
> logically. ... Please, no pedantic discourse explaining why I'm wrong...
> just put in into a PEP and move on.  :)

It does.  "if len(list) == 0"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-08 Thread James Mills
On Mon, May 9, 2011 at 2:34 PM, Ian Kelly  wrote:
> "bool(list)" describes whether the list contains something.  "Not"
> being a logical operator, it stands to reason that "not list" should
> mean the same thing as "not bool(list)".  Anything else would be
> surprising and pointlessly convoluted.  If "not list" bothers you,
> then I would suggest that your problem is actually with "bool(list)".

I concur! +1

>>        ...  should return True only if 'list' is bound to NULL, or if the
>> name 'list' would throw a name exception...

[...]

>>        ...  and, Python should have an explicit way of testing for an empty
>> list that is clear, concise, and easy to understand even for the relatively
>> new Python programmer.  This is not intended to generate counter argument,
>> its just my feedback on a language construct that I find to be inconsistent
>> logically. ... Please, no pedantic discourse explaining why I'm wrong...
>> just put in into a PEP and move on.  :)
>
> It does.  "if len(list) == 0"

Again +1 on the if len(list) == 0:

Now... One thing that really concerns me about the Python
community as a whole is the no. of varying opinions of
"correct" ways of doing things and the distaste for a lot of
things (which in Python are just obvious).

If you are an opinionated individuals and disagree with the
suggestion (even if it is "right"), perhaps keep that to yourself.

if not my_list:

is a perfectly valid and fine idiom to use in Python.

If you prefer some other way, that's fine. Quite frankly
I'm sick of seeing posts that argue for the sake of arguing.

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-09 Thread Terry Reedy

On 5/8/2011 7:36 PM, Dan Stromberg wrote:


On Sun, May 8, 2011 at 3:41 PM, Terry Reedy mailto:tjre...@udel.edu>> wrote:



Because inductive algorithms commonly branch on 'input is something'
(not done, change args toward 'nothing'and recurse or iterate)
versus 'input is nothing (done, return base expression).


Just what is an inductive algorithm?


The parenthesized comments were meant to define common patterns such as:

def f(x):
  if x:
return g(f(reduce_arg(x))
  else:
return base(x)

def f(x)
  ret = start(x)
  while x:
ret = reduce_arg(x)
  return x

More generally, an inductive algorithm computes by looping (with 
recursion or iteration). That is my definition. That includes most of 
the 'interesting' algorithms. You might ask, what is not an inductive 
algorithm? One that does no looping and just returns non-recursive 
expressions, perhaps in multiple branches. The functions in the 
expression are taken as primitives and their internal use of induction 
is ignored. Of course, a computer is nothing but an induction machine:


while not halted:
  get next instruction
  get args
  compute result

Michal Torrie's response is right. Inductive algorithms follow the 
pattern of inductive proofs.


--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-09 Thread harrismh777

Ian Kelly wrote:

"bool(list)" describes whether the list contains something.  "Not"
being a logical operator, it stands to reason that "not list" should
mean the same thing as "not bool(list)".


Ian, James,

   Agreed, and thank you.  This *is* the explanation I was trying to 
prompt D'Aprano for, rather than getting his 'not cat' analogy.


   James, the argument is not for argument sake. The argument is to 
better facilitate understanding for others who are also trying to make 
sense of new ideas, some of whom are lurking.  :)   This argument 
actually goes back to a previous discussion D'Aprano and I (and others) 
were having pertaining to whether software is mathematics.


   It is easy to see how that negating a binary value ( on or off ) 
works with 'not'...   because there are only two possible states.


not on, means off   not off, means on.

Same with '1' and '0'  where we have only two states, or True and False 
where we have only two states... &etc.   But when we have a list, what 
two states are we really discussing?  Aren't we really talking about set 
theory?  A list is an ordered collection of 'stuff' comprising a set. 
Negating the set   'not set'  is saying   'not bool(set)'  /


The two states are either 1) the elements of the set, or 2) not the 
elements of the set--- the empty set, or that 'stuff' outside the set.


The answer to the 'not list' question has to do with the conceived 
semantics of Python ordered collections, which are based more in 
mathematics proper (set theory) than in logic--- the 'not' operator. It 
is better to explain to students where the syntax is based (as Ian did) 
than to state uniformly, "This is just the way Python does it!".


As a side point, the answer, "This is the way Python does it!"... would 
be o.k. if-and-only-if Python were a standardized language, which it 
isn't.   Python's greatest strength is also its greatest weakness... 
that it is constantly evolving through the PEP process. James, one of 
the reasons we argue about language features is for that very purpose 
invited by PEP (and other feedback mechanisms, including this list). The 
community decides over time how Python does things (along with the final 
stamp, I suppose, of Guido the BDFL). So, we must needs be arguing, but 
its not for pedantic squabbling sake   :-)



kind regards,
m harris



--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-09 Thread Steven D'Aprano
On Mon, 09 May 2011 16:58:14 -0500, harrismh777 wrote:

> Ian Kelly wrote:
>> "bool(list)" describes whether the list contains something.  "Not"
>> being a logical operator, it stands to reason that "not list" should
>> mean the same thing as "not bool(list)".
> 
> Ian, James,
> 
> Agreed, and thank you.  This *is* the explanation I was trying to
> prompt D'Aprano for, rather than getting his 'not cat' analogy.

Your dislike of analogies is leading you to see them where they aren't. 
The "cat on the mat" sentence I gave is a concrete example of the use of 
negation in English, not an analogy. It is virtually the opposite of an 
analogy.

In that same post that annoyed you with the cat on the mat example, I 
wrote:

Python uses a boolean algebra where there are many ways of 
spelling the true and false values. The "not" operator returns 
the canonical bool values:

not  returns False
not  returns True

Take note of the distinction between lower-case true/false, 
which are adjectives, and True/False, which are objects of 
class bool.

and later on, I contrasted:

empty list versus non-empty list

Ergo, "not (empty list)" returns True, and "not (non-empty list)" returns 
False, because the empty list is considered false and any non-empty list 
is considered true. I'm sorry that I failed to make that more explicit. 
If I were talking to a programming n00b, I would have been more careful, 
but you've made numerous references to your long, long programming 
experience and I thought you would be able to draw the obvious connection 
without me insulting you by stating the obvious.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-09 Thread Ben Finney
Steven D'Aprano  writes:

> I'm sorry that I failed to make that more explicit. If I were talking
> to a programming n00b, I would have been more careful, but you've made
> numerous references to your long, long programming experience and I
> thought you would be able to draw the obvious connection without me
> insulting you by stating the obvious.

+1 QOTW

-- 
 \   “Never use a long word when there's a commensurate diminutive |
  `\available.” —Stan Kelly-Bootle |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-09 Thread harrismh777

Steven D'Aprano wrote:

 Python uses a boolean algebra where there are many ways of
 spelling the true and false values. The "not" operator returns
 the canonical bool values:



 Take note of the distinction between lower-case true/false,
 which are adjectives, and True/False, which are objects of
 class bool.


   Yes, yes... to your previous comments, and to move the discussion 
forward a bit...


...  the interesting thing about this part of the discussion is the 
class bool... because it looks like 'list' is being 'promoted' to type 
class bool in the following:


if not list:   <=== this is not logical on the surface...

... if the equivalent is:

if not bool(list):   <=== this is more explicit, and more readable 
although it still doesn't tell a casual reader how the bool(list) 
evaluates... is it empty? is it name exception? other?   I'm just 
saying; no need to respond...  just that its easier to understand the 
syntax of 'not list' in the knowledge that what is happening under the 
hood is that the 'not' operator does require a bool() and that list is 
being evaluated bool(list) as one of two logical states.



Having played around a little bit with this today I am again 
impressed that bool() can take *any* object as a parm and derive the 
correct binary state, whatever that happens to be:


bool({}) False
bool([]) False
bool(0)  False
bool('') False
bool(()) False


   Therefore,

   if not str  tests for the empty string...

   if not dict tests for the empty dictionary...

   &etc.


... is at least consistent ...


kind regards,
m harris



--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-09 Thread harrismh777

Steven D'Aprano wrote:

If I were talking to a programming n00b, I would have been more careful,
but you've made numerous references to your long, long programming
experience and I thought you would be able to draw the obvious connection
without me insulting you by stating the obvious.


Pedantics is always potentially insulting, which was your intent, me 
thinks. Whether I choose to be insulted is my own prerogative, and I 
choose to 'not' be insulted. I would only suggest an argumentation style 
that is clear, 'not' pedantic, and 'not' potentially insulting when 
possible. (not necessarily for my sake)


uh,  not bool(insulting)




kind regards,
m harris

--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On 07 May 2011 02:51:50 GMT, Steven D'Aprano
   wrote:
:  On Fri, 06 May 2011 14:57:21 -0700, scattered wrote:
: 
: > is there any problem with
: > 
: > (3) if li == []:
: > 
: > ?
: > 
: > Seems to work when I test it and seems to clearly test what you are
: > trying to test. The only problem might be if in some contexts == has the
: > semantics of checking for object identity.
: 
:  Yes, if li == [] works too. But how do you know li is a list and not some 
:  other sequence type?

It says so in the Subject header :-)

:  The advantage of the "if x" test is that it is independent of the type of 
:  x.

Sure, but the question wasn't ...

The problem with 'if x' is that it requires a much more detailed 
understanding of python.  li == [] is as explicit as it gets, and
leaves no room for doubt.  len(li) == 0 is almost as explicit and
much more flexible.  Just x is as generic as it gets, but depends
on python's convolved rules for duck processing and if you aim at
legibility it is better avoided.


-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On 07 May 2011 02:49:53 GMT, Steven D'Aprano
   wrote:
:  On Fri, 06 May 2011 16:05:09 -0400, Adam Tauno Williams wrote:
: 
: > I'd never accept code like "if not x" as an empty test.
: 
:  So much the worse for you then.
: 
:  The point of the "if x" idiom is that it is a polymorphic test which is 
:  independent of the type.

Normally, polymorphisms implies multiple forms only, where the different
forms has some form of common interpretation.  That's what makes
polymorphism useful and helpful, increasing legibility.

In this case, the interpretation of an arbitrary object as a boolean
is peculiar for python.  An empty list is a real, existing object, and 
the supposition that [] be false is counter-intuitive.  It can be
learnt, and the shorthand may be powerful when it is, but it will 
confuse many readers.

-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Laurent Claessens

In this case, the interpretation of an arbitrary object as a boolean
is peculiar for python.  An empty list is a real, existing object, and
the supposition that [] be false is counter-intuitive.  It can be
learnt, and the shorthand may be powerful when it is, but it will
confuse many readers.


Once I wrote something like:

def f(x=None):
   if x:
  print x
   else:
  print "I have no value"


The caller of that function was something like f(cos(2*theta)) where 
theta come from some computations.


Well. When it turned out that theta was equal to pi/4, I got "I have no 
value". I spent a while to figure out the problem :)


Conclusion: the boolean value of an object is to be used with care in 
order to tests if an optional parameter is given or not (when default 
value is None).



Have a good noon
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On Sat, 07 May 2011 21:57:13 -0700, Ethan Furman
   wrote:
:  If you're going to use a language, and use it well, you have to learn 
:  how that language works.

And if the world evolves around the compiler and you, that advice
suffices.

However, programming is often as much about developing ideas in a large
and complex community, where perfect universal mastery of one language
is not an option, because half the community do not normally use that
language or aren't really programmers at all.  The less you assume about
the skill of the reader, the better it is.

-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Steven D'Aprano
On Wed, 11 May 2011 11:48:16 +0200, Laurent Claessens wrote:

> Once I wrote something like:
> 
> def f(x=None):
> if x:
>print x
> else:
>print "I have no value"
> 
> 
> The caller of that function was something like f(cos(2*theta)) where
> theta come from some computations.
> 
> Well. When it turned out that theta was equal to pi/4, I got "I have no
> value". I spent a while to figure out the problem :)

I believe you are grossly oversimplifying whatever code you had. Using 
the definition of f from above:

>>> theta = math.pi/4
>>> f(math.cos(2*theta))
6.12303176911e-17

But even if you rounded the result of cos(2*theta) to zero, you will get 
the same result regardless of whether you test for "if x" or "if x != 0".


> Conclusion: the boolean value of an object is to be used with care in
> order to tests if an optional parameter is given or not (when default
> value is None).

Or, to put it another way: if you want to test for an object being None, 
test for the object being None.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Laurent Claessens



I believe you are grossly oversimplifying whatever code you had. Using
the definition of f from above:


 theta = math.pi/4
 f(math.cos(2*theta))

6.12303176911e-17


Yes: its oversimplifued. The angle come from a normal vector of a curve 
and so on In particular, I was using Sage; the computations are 
exact: pi is pi and cos(pi) is zero.



 Conclusion: the boolean value of an object is to be used with care in
 order to tests if an optional parameter is given or not (when default
 value is None).


Or, to put it another way: if you want to test for an object being None,
test for the object being None.


It was my conclusion too ;)

Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Laurent Claessens



I believe you are grossly oversimplifying whatever code you had. Using
the definition of f from above:


 theta = math.pi/4
 f(math.cos(2*theta))

6.12303176911e-17


Yes: its oversimplifued. The angle come from a normal vector of a curve 
and so on In particular, I was using Sage; the computations are 
exact: pi is pi and cos(pi) is zero.



 Conclusion: the boolean value of an object is to be used with care in
 order to tests if an optional parameter is given or not (when default
 value is None).


Or, to put it another way: if you want to test for an object being None,
test for the object being None.


It was my conclusion too ;)

Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Steven D'Aprano
On Wed, 11 May 2011 10:02:42 +0100, Hans Georg Schaathun wrote:

> The problem with 'if x' is that it requires a much more detailed
> understanding of python.

"Much" more detailed? Hardly.

Understanding that Python accepts any and all objects in truth-testing 
concepts, and the rules thereof, is Python 101 territory. It's beginner-
level knowledge. It is far less advanced than the knowledge that ** is 
used for exponentiation. After all, many programmers have never needed to 
raise a number to a power, and might not learn about it for years, but 
every programmer writes if or while statements at some point.

Not knowing that you can write "if x" instead of "if x == []" is like not 
knowing that you can write 

elif condition

instead of 

else:
if condition

If somebody were to argue that it is "better to write else if explicitly, 
instead of the confusing elif", we'd all laugh at them.

Every time the question of conditional testing comes up here, it never 
ceases to astonish me how many developers argue against learning the 
idioms of the language, and prefer to re-use the idioms of other 
languages in Python.

Python is an object-oriented language where objects get to decide for 
themselves whether they should be treated as true or false. Writing:

if x == []:

instead of 

if x:

merely[1] because you worry that it isn't explicit enough, or could 
confuse other developers, or out of some nagging concern that maybe 
Python will do the wrong thing[2] unless you hold its hand through the 
process, is as silly as writing this:

count = 0
for item in x:
count += 1


instead of:

count = len(x)

(As silly, but not as verbose.)

I don't mean to insult anyone, but I've heard and read all the arguments 
against Python's truth-testing, and they don't impress me in the 
slightest. Most of them strike me as silly. The only argument that 
carries any weight to me is one which I haven't seen anyone raise:

"if x:" turns something which arguably could have been a mistake ("oops, 
I forgot to write the condition!") into valid code.





[1]  It may be that there are good, solid reasons for writing explicit 
len(x)==0 tests, although I'm hard-pressed to think of any. The closest I 
come to is when you wish to emphasize "equal to some number that just 
happens to be zero" rather than "it's a false/empty value". If so, you 
get a free pass to write the test the long way. E.g. you might write 
"x % 2 == 1" rather than just "x % 2" because you want to highlight that 
the remainder equals one, rather than the remainder merely being a true 
value.


[2]  Of course, a custom object x might misbehave when you test it for 
truth value. That would be a bug, just like it would be a bug if it 
misbehaved when you call len(x) == 0. If you can't trust "if x" to work, 
what makes you think you can trust "len(x) == 0" either?


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Steven D'Aprano
On Wed, 11 May 2011 10:14:38 +0100, Hans Georg Schaathun wrote:

> In this case, the interpretation of an arbitrary object as a boolean is
> peculiar for python.  

Incorrect. It is widespread among many languages. Programmers have been 
writing conditional tests using arbitrary values since 1958 when Lisp 
introduced the concept.

C, Forth and Visual Basic treat any non-zero number as true, and zero as 
false; that's not quite arbitrary objects, but it's arbitrary integer 
values. Similarly, Objective C has two different boolean types, "BOOL" 
which is a C char where 0 is false and everything else is true, and 
"bool" which is more like the Java boolean type.

Perl treats the empty string, "0", 0 and undefined variables as false, 
and everything else as true.

Ruby treats null and false as false, and everything else as true.

JavaScript treats "", null, undefined, NaN, 0 and false as false values, 
and everything else as true.

PHP treats FALSE, 0, "", "0", empty arrays, objects with no member 
variables, NULL, unset variables, and SimpleXML objects created from 
empty tags as false, everything else as true.

Clojure treats nil and false as false, everything else as true.

SQL's boolean type has three or four values: true, false, null and 
unknown, where implementations are free to treat null and unknown as 
either the same or different values. (So a 3 or 4 value logic, not 
actually Boolean at all.)

So Python is hardly unique, nor is this some new-fangled innovation.



> An empty list is a real, existing object, and the
> supposition that [] be false is counter-intuitive.

Not to me, nor to anyone who has an intuition about "something" versus 
"nothing". I believe this distinction is fundamental to the universe, and 
that nearly every person understands this intuitively. The distinction 
between something and nothing is so strong that it took centuries of 
argument for the finest minds in Europe[1] to finally decide that, yes, 
zero is a number -- and they only did it because the Arabs and Indians 
had proven how useful it was, and Roman numerals really do suck for doing 
calculations.



> It can be learnt,
> and the shorthand may be powerful when it is, but it will confuse many
> readers.

In my experience, it does not confuse newbies or beginners. The only 
people it confuses are those who are over-educated into thinking that the 
One Correct Way of doing truth testing is with a dedicated boolean type, 
and anything else is heresy.


[1] At least is you asked them.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Steven D'Aprano
On Wed, 11 May 2011 11:47:42 +0100, Hans Georg Schaathun wrote:

> On Sat, 07 May 2011 21:57:13 -0700, Ethan Furman
>wrote:
> :  If you're going to use a language, and use it well, you have to learn
> :  how that language works.
> 
> And if the world evolves around the compiler and you, that advice
> suffices.
> 
> However, programming is often as much about developing ideas in a large
> and complex community, where perfect universal mastery of one language
> is not an option, because half the community do not normally use that
> language or aren't really programmers at all.  The less you assume about
> the skill of the reader, the better it is.

Do you think that we should avoid chained comparisons, class methods, 
closures, co-routines, decorators, default values to functions, 
delegation, doc tests, exceptions, factory functions, generator 
expressions, inheritance, iterators, list comprehensions, operator 
overloading, properties, regular expressions, tuple unpacking, or unit 
tests, to say nothing of *advanced* techniques like descriptors or 
metaclasses, just in case the person reading your code is a clueless n00b?

We routinely and uncontroversially use all of these techniques (well, 
sometimes metaclasses get a few raised eyebrows). Truth testing is MUCH 
simpler than any of those.

It is extremely patronizing to say that we should avoid truth-testing 
arbitrary objects because it is too complicated for other people. It's 
not hard, and they can learn.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On 11 May 2011 13:36:02 GMT, Steven D'Aprano
   wrote:
: > In this case, the interpretation of an arbitrary object as a boolean is
: > peculiar for python.  
: 
:  Incorrect. It is widespread among many languages. Programmers have been 
:  writing conditional tests using arbitrary values since 1958 when Lisp 
:  introduced the concept.

The fact that you need to list language by language which objects
evaluate as false or equivalent to false illustrates that this has
to be learnt language by language.  Allowing arbitrary objects is
one thing, the particular interpretation is peculiar.

The fact that if and while accepts any object for the condition may
be chapter 1 stuff, but the memorisation of exactly how the
interpretation does not come early (unless you learn it by rote of
course).

:  C, Forth and Visual Basic treat any non-zero number as true, and zero as 
:  false; that's not quite arbitrary objects, but it's arbitrary integer 
:  values. Similarly, Objective C has two different boolean types, "BOOL" 
:  which is a C char where 0 is false and everything else is true, and 
:  "bool" which is more like the Java boolean type.

Mentioning C, with no Boolean type at all, in this context is a bit
absurd.  Understanding boolean evaluation in C is very little help
when you want to understand it in python.

: > An empty list is a real, existing object, and the
: > supposition that [] be false is counter-intuitive.
: 
:  Not to me, nor to anyone who has an intuition about "something" versus 
:  "nothing". I believe this distinction is fundamental to the universe, and 
:  that nearly every person understands this intuitively. The distinction 
:  between something and nothing is so strong that it took centuries of 
:  argument for the finest minds in Europe[1] to finally decide that, yes, 
:  zero is a number -- and they only did it because the Arabs and Indians 
:  had proven how useful it was, and Roman numerals really do suck for doing 
:  calculations.

Exactly.  By now we have gotten past that old-fashioned idea that 0
is not a number.  Computer scientists even tend to count 0 as a
natural number.  When 0 is a number as real and existent as any other,
one would think that the empty list is also as real and existent as
any other list.

:  In my experience, it does not confuse newbies or beginners. The only 
:  people it confuses are those who are over-educated into thinking that the 
:  One Correct Way of doing truth testing is with a dedicated boolean type, 
:  and anything else is heresy.

What kind of beginners are you talking about?  Beginners to python
or beginners to programming.

The audience I am concerned about is the ones who are over-educated 
into using and having used a score of different meanings of the same
symbols.  They will be used to their intuition being wrong when they
move into a new context.  Being explicit will help them.


-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On 11 May 2011 12:14:46 GMT, Steven D'Aprano
   wrote:
:  Not knowing that you can write "if x" instead of "if x == []" is like not 
:  knowing that you can write 
: 
:  elif condition
: 
:  instead of 
: 
:  else:
:  if condition

My concern was with the reader and not the writer.

What could elif mean other than else: if?

if x could, for instance,  mean "if x is defined".


-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread D'Arcy J.M. Cain
On Wed, 11 May 2011 11:47:42 +0100
Hans Georg Schaathun  wrote:
> However, programming is often as much about developing ideas in a large
> and complex community, where perfect universal mastery of one language
> is not an option, because half the community do not normally use that
> language or aren't really programmers at all.  The less you assume about
> the skill of the reader, the better it is.

Non-programmers should be able to program?

Should non-doctors be able to doctor?  Should cars be built so that
anyone can intuitively fix them without a mechanic?  Should trucks be
built so that drivers don't have to learn how to split shift?  Why is
programming so different that we can't expect people to actually learn
their discipline?

This discussion is giving me some insight into some of the crap
programming I see these days.

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread D'Arcy J.M. Cain
On Wed, 11 May 2011 15:05:45 +0100
Hans Georg Schaathun  wrote:
> What could elif mean other than else: if?

If run by an elf?  Who knows.  You do, of course, if you have learned
the basics of the language you are using.

> if x could, for instance,  mean "if x is defined".

It could also mean "if x was created on a Tuesday."  A short
introduction to the language explains what it actually means.

When did we come to the idea that people should be able to program in a
language without actually learning it?  The fact that Python comes so
close to that possibility is nothing short of revolutionary.  I suppose
one day a reasoning android will be able to sit down at the terminal of
a star ship computer and ask simple questions while making random hand
movements across a screen but for now I am afraid that programmers
still have to learn programming.

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On 11 May 2011 13:45:52 GMT, Steven D'Aprano
   wrote:
:  Do you think that we should avoid chained comparisons, class methods, 
:  closures, co-routines, decorators, default values to functions, 
:  delegation, doc tests, exceptions, factory functions, generator 
:  expressions, inheritance, iterators, list comprehensions, operator 
:  overloading, properties, regular expressions, tuple unpacking, or unit 
:  tests, to say nothing of *advanced* techniques like descriptors or 
:  metaclasses, just in case the person reading your code is a clueless n00b?

Not at all.  On both accounts.
1. My concern was not about clueless newbies.  They need to
  learn.  My concern is about experienced scientists and engineers 
  who are simply new to python.  They will be dealing with a dozen
  different languages (programming and otherwise), with a need to
  read more languages than they can possibly learn to master.

2. You should avoid constructs which can /reasonably/ be avoided to 
  /increase/ legibility.  Writing if x for if len(x) > 0 when you
  know that x is of some sort of collection type with len defined
  does nothing to help legibility.  Many of the socalled advanced
  constructs you mention are used to increase legibility one way or
  another.  Others will simply allow functionality which would otherwise
  be impossible.

  I don't object to using if x in a case where x may or may not have
  len() defined.

:  We routinely and uncontroversially use all of these techniques (well, 
:  sometimes metaclasses get a few raised eyebrows). Truth testing is MUCH 
:  simpler than any of those.

Simpler, yes, but it surely depends on more detailed knowledge.  One has
to remember how the boolean conversion works, for each possible data type.
This requires looking up the rules for each data type.

E.g. Anyone who has used list/set comprehension in Z, haskell, set theory,
or whereever will understand python list comprehension immediately.

:  It is extremely patronizing to say that we should avoid truth-testing 
:  arbitrary objects because it is too complicated for other people. It's 
:  not hard, and they can learn.

Again you miss the point.  It is not /too/ complicated.
It is /unnecessarily/ complicated.  You don't noticeably
gain anything by using if x instead of if len(x) > 0, if
you know that the latter is defined.  

If everyone who ever needs to see your program is a python
programmer, then your approach works as well as mine.  

-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Chris Angelico
On Thu, May 12, 2011 at 12:00 AM, Hans Georg Schaathun  
wrote:
> The fact that you need to list language by language which objects
> evaluate as false or equivalent to false illustrates that this has
> to be learnt language by language.  Allowing arbitrary objects is
> one thing, the particular interpretation is peculiar.

Languages have to be learned language by language. Yes, you want to be
similar to others if you can (and in 'most every language where it's
legal syntax, "1+2" will mean "3"), but whenever I'm working in a
language with which I'm not _really_ fluent, I like to keep an
operator table handy (precedence, plus oddments like what the
exponentiation operator is, or whether & is bitwise or boolean). They
do differ, and if I'm writing in PHP or Python or Pike or C++ or Java
or whatever else it be, I have to use the operators the way the
interpreter/compiler will understand them, not in some other way that
I "deem better".

> Mentioning C, with no Boolean type at all, in this context is a bit
> absurd.  Understanding boolean evaluation in C is very little help
> when you want to understand it in python.

Actually, it's not.

# Python code:
if x:
 statements

/* C code: */
if (x) {
 statements;
}

What's the difference? Both of them let you test the truth of some
arbitrary object or expression, and neither of those statements
implies a Boolean type. In C++, this is exploited extensively with,
for instance, the stream I/O objects evaluating as false when in an
error or EOF state:

while (infile) infile >> *ptr++; // Compact and convenient way to read
into an array

Actually that one can be combined down even further, but for clarity I
leave it like that.

Chris Angelico
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Redcat
On Wed, 11 May 2011 10:33:51 -0400, D'Arcy J.M. Cain wrote:

> Non-programmers should be able to program?

Wasn't that sort of the premise behind Visual Basic? I don't know if that 
was the intention, but it sure was the result in a lot of cases.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Ethan Furman

Hans Georg Schaathun wrote:

On 11 May 2011 13:36:02 GMT, Steven D'Aprano
   wrote:
: > In this case, the interpretation of an arbitrary object as a boolean is
: > peculiar for python.  
: 
:  Incorrect. It is widespread among many languages. Programmers have been 
:  writing conditional tests using arbitrary values since 1958 when Lisp 
:  introduced the concept.


The fact that you need to list language by language which objects
evaluate as false or equivalent to false illustrates that this has
to be learnt language by language.  Allowing arbitrary objects is
one thing, the particular interpretation is peculiar.



Like so many other things Python got right, I think it got this right as 
well.  "something" vs "nothing" is simple, useful, and easy to remember.




By now we have gotten past that old-fashioned idea that 0
is not a number.  Computer scientists even tend to count 0 as a
natural number.  When 0 is a number as real and existent as any other,
one would think that the empty list is also as real and existent as
any other list.


Python is not concerned with whether it exists -- that's a name binding; 
 Python is concerned with whether anything is there.  0 apples is 
nothing and a an empty list is nothing as well.


~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Steven D'Aprano
On Wed, 11 May 2011 15:05:45 +0100, Hans Georg Schaathun wrote:

> My concern was with the reader and not the writer.
> 
> What could elif mean other than else: if?

It could mean "Oh, the author has made a stupid typo, I better fix it."

It could mean "What does the elif command do?"

The first time I read Python code, I had literally no idea what to make 
of elif. It seemed so obvious to me that any language would let you write 
"else if ..." (on a single line) that I just assumed that elif must be 
some other construct, and I had no idea what it was. It never even 
crossed my mind that it could be "else if" rammed together into one word.

I soon learned better though.

Once you start dumbing down your code for readers who don't know your 
language, it's a race to the bottom. There's very little you can write 
that *somebody* won't misunderstand.



> if x could, for instance,  mean "if x is defined".

Yes it could, if you're programming in Perl. But we're not.

When I write a sentence in English, and I use the word "gift" to mean a 
thing which is given, I don't worry that German or Swedish readers will 
think I'm talking about poison. If I use "preservative", I mean something 
which preserves, and if Italian and Spanish readers mistake it for a 
condom, that's their problem, not mine. Writing code is no different. 
When I'm coding in Python, I use Python rules and meanings, not some 
other language.

Why should I code according to what some hypothetical Python dummy 
*might* think the code will do, instead of what the code *actually* does?



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Chris Angelico
On Thu, May 12, 2011 at 1:50 AM, Steven D'Aprano
 wrote:
> On Wed, 11 May 2011 15:05:45 +0100, Hans Georg Schaathun wrote:
>
>> My concern was with the reader and not the writer.
>>
>> What could elif mean other than else: if?
>
> The first time I read Python code, I had literally no idea what to make
> of elif. It seemed so obvious to me that any language would let you write
> "else if ..." (on a single line) that I just assumed that elif must be
> some other construct, and I had no idea what it was. It never even
> crossed my mind that it could be "else if" rammed together into one word.

In a Bourne shell script, if ends with fi... case ends with esac... so
file would end with... hmm. Yeah, I think it's best to know the
language you're trying to comprehend, and/or actually look at context
instead of shoving a piece of code under someone's nose and saying "I
bet you can't figure out what THIS does!".

Chris Angelico
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Steven D'Aprano
On Wed, 11 May 2011 15:34:28 +0100, Hans Georg Schaathun wrote:

> On 11 May 2011 13:45:52 GMT, Steven D'Aprano
>wrote:
> :  Do you think that we should avoid chained comparisons, class methods,
> :  closures, co-routines, decorators, default values to functions, : 
> delegation, doc tests, exceptions, factory functions, generator : 
> expressions, inheritance, iterators, list comprehensions, operator : 
> overloading, properties, regular expressions, tuple unpacking, or unit :
>  tests, to say nothing of *advanced* techniques like descriptors or : 
> metaclasses, just in case the person reading your code is a clueless
> n00b?
> 
> Not at all.  On both accounts.
> 1. My concern was not about clueless newbies.  They need to
>   learn.  My concern is about experienced scientists and engineers who
>   are simply new to python.

Which makes them clueless newbies *about Python*. I don't care how 
experienced they are in astrophysics or biology or calculating the 
average airspeed of an unladen swallow.


>   They will be dealing with a dozen different
>   languages (programming and otherwise), with a need to read more
>   languages than they can possibly learn to master.

Yeah, life is hard and then you die, and scientists don't even get paid 
that much. So what? Do physicists write their scientific papers about 
string theory with the thought "What if some Python programmer who knows 
nothing about string theory is reading this? I better dumb it down."

Of course not. A ridiculous idea. They use their tools the way they are 
designed to be used, and outsiders have to learn the language and the 
jargon to make sense of it. This is not a problem that needs solving.

It's one thing to simplify code that you are explicitly using as a 
teaching aid. That's a good thing, I approve of that. But it's a 
completely different thing to dumb down production code because you think 
some non-programmer might have to read it.



> 2. You should avoid constructs which can /reasonably/ be avoided to
>   /increase/ legibility.  Writing if x for if len(x) > 0 when you know
>   that x is of some sort of collection type with len defined does
>   nothing to help legibility.

Of course it does. 

It means you don't have to care about implementation details of what 
emptiness means for a list. It means you don't force the reader to read, 
parse and understand three extraneous terms. It means you don't force the 
reader to wonder why you bothered to use a long-winded test when a short 
test would do, or be concerned that maybe > 0 is a typo and you actually 
meant > 10.


[...]
> Simpler, yes, but it surely depends on more detailed knowledge.  One has
> to remember how the boolean conversion works, for each possible data
> type. This requires looking up the rules for each data type.

No. You have that exactly backwards. The point of "if x" is that you 
DON'T have to care about how the boolean conversion works, because the 
object itself encapsulates that behaviour. This is basic object-oriented 
principles.

When you call len(x) you don't care about the details of how to calculate 
the length of x. The object itself knows so that you don't have to. The 
same applies to truth testing.

I have a data type that is an array of lists. When you call "if len(x) > 
0" on it, it will blow up in your face, because len(x) returns a list of 
lengths like [12, 0, 2, 5]. But if you say "if x", it will do the right 
thing. You don't need to care how to truth-test my data type, because it 
does it for you. By ignoring my type's interface, and insisting on doing 
the truth-test by hand, you shoot yourself in the foot.



> E.g. Anyone who has used list/set comprehension in Z, haskell, set
> theory, or whereever will understand python list comprehension
> immediately.

Yes. And anyone who hasn't, probably won't. But they will learn.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Ian Kelly
On Wed, May 11, 2011 at 8:34 AM, Hans Georg Schaathun  
wrote:
> E.g. Anyone who has used list/set comprehension in Z, haskell, set theory,
> or whereever will understand python list comprehension immediately.

They would understand the underlying concept.  But would somebody who
is not a Python programmer intuitively understand the difference
between this:

[x + 3 for x in xs if x % 2 == 1]

and this:

{x + 3 for x in xs if x % 2 == 1}

and this:

(x + 3 for x in xs if x % 2 == 1)

Somebody with rudimentary Python knowledge might even reason that
since the first two create a list and a set respectively, the third
must therefore create a tuple, which is wrong.

None of this should be taken as an argument against using generator expressions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Eric Snow
All of this just boils down to Python providing an implicit bool cast in
syntactic situations that expect conditional expressions, including if [1].
 So "if x:" is equivalent to "if bool(x)".  Perhaps that is the part that is
not immediately obvious, being implicit to Python conditional syntax.

Python also provides a mechanism for customization of a wide variety of
behavior that is not obvious without reading the [excellent] documentation
[2].  So the following three forms will implicitly call the special method
names:

if x:  =>  if bool(x):  =>  if x.__bool__():  [3]

if x == []:  =>  if x.__eq__([]):

if len(x) == 0:  =>  if x.__len__() == 0:

Other than the implicit cast to bool for conditional syntax and the implicit
calls to special method names as appropriate I am not clear that there is
any remaining mystery for this question.  And the language reference makes
all of the above very clear, so I highly recommend it.

The only caveat is that builtin types don't always act the same way as user
defined types (classes).  Not sure if the few differences are well
documented, but to be honest that hasn't bit me hard enough that I needed to
look it up.  I do know that the builtin list has a __eq__ method and a
__len__ method, but not a __bool__ method (which it doesn't need [3]).

-eric

[1]
http://docs.python.org/dev/py3k/reference/compound_stmts.html#the-if-statement
[2]
http://docs.python.org/dev/py3k/reference/datamodel.html#special-method-names
[3] http://docs.python.org/dev/py3k/reference/datamodel.html#object.__bool__
so if __bool__ doesn't exist it tries __len__ and so forth.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: checking if a list is empty

2011-05-11 Thread Prasad, Ramit
> I don't mean to insult anyone, but I've heard and read all the arguments 
> against Python's truth-testing, and they
>don't impress me in the slightest. Most of them strike me as silly. The only 
>argument that carries any weight to me is
>one which I haven't seen anyone raise:

>"if x:" turns something which arguably could have been a mistake ("oops, I 
>forgot to write the condition!") into valid
>code.

The only problem I have had with the "if x:" notation is when I have values 
that might be empty lists, empty strings, None, or a boolean value being 
returned from the same source. But this is probably an instance when a good 
programmer would explicitly check the type instead of the naive "if x:" 
notation.

On the other hand, as a fairly n00b Python (and n00b Perl) developer, I find 
the notation "if not x:" to be far more English readable than "if x==None or 
len(x)== 0 or x==0 or bool(x):" (or some derivative/combination of those). 



Ramit

Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423
This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: checking if a list is empty

2011-05-11 Thread Prasad, Ramit
>The audience I am concerned about is the ones who are over-educated 
>into using and having used a score of different meanings of the same
>symbols.  They will be used to their intuition being wrong when they
>move into a new context.  Being explicit will help them.

I find this argument to be flawed. Should I stop using built-in generators 
instead of range/xrange for looping through lists? Certainly for loops with 
loop counting are understood more widely than generators. Should I stop using 
any advanced feature Python because it is difficult to understand without 
knowing Python?

I do not code for absolute beginner in Python to read my code. That way lies 
madness! I code with the assumption that someone with intermediate knowledge 
can read my code (unless I am forced into optimizing and then I rely on 
comments to explain). Actually, that is how I attempt to code in any language.

I may not have made the point well, but I cannot see any advantage for trying 
to program for the lowest common denominator.


Ramit



Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On Wed, 11 May 2011 10:33:51 -0400, D'Arcy J.M. Cain
   wrote:
:  Non-programmers should be able to program?

That was not really what I suggested; I was primarily talking
about reading programs and commenting on formulæ and algorithms.

:  Should non-doctors be able to doctor?

If I were God, I might consider simplifying the anatomy to allow that,
yes.

:Should cars be built so that
:  anyone can intuitively fix them without a mechanic?  Should trucks be
:  built so that drivers don't have to learn how to split shift?

That's out of my area so I don't know.  However, contrary to
software, I have never seen any use of rebuilding the car to
do something other than transport ...

And, besides, as mechanics do not design cars or even engines, they 
are not analogous to programmers, but rather to computer technicians 
(maintenance, deployment, installation, etc).

: Why is
:  programming so different that we can't expect people to actually learn
:  their discipline?

It is not different from other engineering disciplines, where you would
have to interact with experts from other disciplines, and understand
and comment on their designs.  That's the way to build a /system/.

Say, you want to create the software to make weather forcasts.
At the end of the day, that's programming, but no way that's going
to be a task for programmers alone.  You need mathematicians,
algorithm theorists, physicists, programmers, and multiple 
specialisations within each discipline.  If you can make your 
programs clear enough to be used as a language of communications, 
you will simplify the development, and allow the code to be
validated by those who knows how the computation has to be done
without specialising in talking to the computer.

:  This discussion is giving me some insight into some of the crap
:  programming I see these days.

I wonder if you would do a better job at programming the software
to crack equations from quantum physics than the physicist :-)

-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On 11 May 2011 16:26:40 GMT, Steven D'Aprano
   wrote:
: > 1. My concern was not about clueless newbies.  They need to
: >   learn.  My concern is about experienced scientists and engineers who
: >   are simply new to python.
: 
:  Which makes them clueless newbies *about Python*. I don't care how 
:  experienced they are in astrophysics or biology or calculating the 
:  average airspeed of an unladen swallow.

Someone who knows how to program is never clueless starting a new
language.  Newbie, may be, but he knows most of the constructions
and semantic principles to look for; most of it is learning the syntax.

:  Yeah, life is hard and then you die, and scientists don't even get paid 
:  that much. So what? Do physicists write their scientific papers about 
:  string theory with the thought "What if some Python programmer who knows 
:  nothing about string theory is reading this? I better dumb it down."

That depends on the purpose of that particular paper, but the real 
question is, who writes the software to test that string theory 
empirically?  Please tell.

-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On Thu, 12 May 2011 02:05:21 +1000, Chris Angelico
   wrote:
:  In a Bourne shell script, if ends with fi... case ends with esac... so
:  file would end with... hmm. Yeah, I think it's best to know the
:  language you're trying to comprehend, and/or actually look at context
:  instead of shoving a piece of code under someone's nose and saying "I
:  bet you can't figure out what THIS does!".

Code is quite often published to document algorithms, methods and
formulæ for the purpose of scientific research.  Since there is no
universal language which suits everything and everyone, this
is exactly what happens.  One has to have the rudimentary knowledge
to read half a dozen different languages to be able to read the
code and extract the algorithms.  If one tried to maintain the
necessary programming skills to exploit all of those languages to
their full potential, one would simply not be able to keep up with
the application discipline.

If all you do is to write software for computer illiterate users, YMWV.

-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On Wed, 11 May 2011 10:27:49 -0400, D'Arcy J.M. Cain
   wrote:
:  When did we come to the idea that people should be able to program in a
:  language without actually learning it?  The fact that Python comes so
:  close to that possibility is nothing short of revolutionary.

Revolutionary indeed, so why don't we exploit the revolution
and write the programs to be as accessible as possible?

(Although, python is not the most revolutionary in this respect.)

-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On Wed, 11 May 2011 10:31:59 -0600, Ian Kelly
   wrote:
:  (x + 3 for x in xs if x % 2 == 1)

Interesting.  Thanks.  That might come in handy some time.

-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On Wed, 11 May 2011 13:50:54 -0400, Prasad, Ramit
   wrote:
:  I find this argument to be flawed. Should I stop using built-in 
: generators instead of range/xrange for looping through lists?
: Certainly for loops with loop counting are understood more widely
: than generators. Should I stop using any advanced feature Python
: because it is difficult to understand without knowing Python?

No; I'd suggest the most legible and intuitive construct that /does/ the
job.  Never something which requires one extra (illegible) page to do
the job, or something which does not do the job at all.

:  I may not have made the point well, but I cannot see any advantage 
: for trying to program for the lowest common denominator.

Common to what?  I'd try the lowest common denominator of
legibility and effictiveness.

It is just KISS.

-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: checking if a list is empty

2011-05-11 Thread Prasad, Ramit
>Common to what?  I'd try the lowest common denominator of
>legibility and effictiveness.
>It is just KISS.

Fair enough. I am a sheep, so I do what other (more knowledgeable) people do. 
It is a fair assumption (for my specific code writing environments) that 
everyone who is going to read my code understands "if x:" notation or is 
expected to learn enough Python to understand it.




Ramit



Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423


-Original Message-
From: python-list-bounces+ramit.prasad=jpmchase@python.org 
[mailto:python-list-bounces+ramit.prasad=jpmchase@python.org] On Behalf Of 
Hans Georg Schaathun
Sent: Wednesday, May 11, 2011 1:16 PM
To: python-list@python.org
Subject: Re: checking if a list is empty

On Wed, 11 May 2011 13:50:54 -0400, Prasad, Ramit
   wrote:
:  I find this argument to be flawed. Should I stop using built-in 
: generators instead of range/xrange for looping through lists?
: Certainly for loops with loop counting are understood more widely
: than generators. Should I stop using any advanced feature Python
: because it is difficult to understand without knowing Python?

No; I'd suggest the most legible and intuitive construct that /does/ the
job.  Never something which requires one extra (illegible) page to do
the job, or something which does not do the job at all.

:  I may not have made the point well, but I cannot see any advantage 
: for trying to program for the lowest common denominator.

-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list
This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Ethan Furman

Hans Georg Schaathun wrote:

On Wed, 11 May 2011 13:50:54 -0400, Prasad, Ramit
   wrote:
:  I find this argument to be flawed. Should I stop using built-in 
: generators instead of range/xrange for looping through lists?

: Certainly for loops with loop counting are understood more widely
: than generators. Should I stop using any advanced feature Python
: because it is difficult to understand without knowing Python?

No; I'd suggest the most legible and intuitive construct that /does/ the
job.  Never something which requires one extra (illegible) page to do
the job, or something which does not do the job at all.

:  I may not have made the point well, but I cannot see any advantage 
: for trying to program for the lowest common denominator.


Common to what?  I'd try the lowest common denominator of
legibility and effictiveness.

It is just KISS.


'if li' *is* KISS.

~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Chris Torek
In article <4dcab8bf$0$29980$c3e8da3$54964...@news.astraweb.com>
Steven D'Aprano   wrote:
>When you call len(x) you don't care about the details of how to calculate 
>the length of x. The object itself knows so that you don't have to. The 
>same applies to truth testing.
>
>I have a data type that is an array of lists. When you call "if len(x) > 
>0" on it, it will blow up in your face, because len(x) returns a list of 
>lengths like [12, 0, 2, 5]. But if you say "if x", it will do the right 
>thing. You don't need to care how to truth-test my data type, because it 
>does it for you. By ignoring my type's interface, and insisting on doing 
>the truth-test by hand, you shoot yourself in the foot.

What this really points out is that "if x" and "if len(x) > 0" are
*different tests*.  Consider xml.etree.ElementTree "Element" objects.
The documentation says, in part:

In ElementTree 1.2 and earlier, the sequence behavior means
that an element without any subelements tests as false (since
it's an empty sequence), even if it contains text and
attributions. ...

Note: This behavior is likely to change somewhat in ElementTree
1.3.  To write code that is compatible in both directions, use
... "len(element)" to test for non-empty elements.

In this case, when x is an Element, the result of bool(x) *could*
mean just "x has sub-elements", but it could also/instead mean "x
has sub-elements, text, or attributions".

The issue raised at the beginning of this thread was: which test
is "better" when x is a list, the test that invokes bool(x), or
the test that invokes len(x)?  There is no answer to that, any more
than there is to which ice cream flavor is "best". [%]  A more
interesting question to ask, in any given bit of code, is whether
bool(x) or len(x) is more appropriate for *all* the types x might
take at that point, rather than whether one or the other is better
for lists, where the result is defined as equivalent.

(The biggest problem with answering that tends to be deciding
what types x might take.)

[% Chocolate with raspberry, or mint, or similar.]
-- 
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)  http://web.torek.net/torek/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: checking if a list is empty

2011-05-11 Thread Prasad, Ramit
> Someone who knows how to program is never clueless starting a new
>language.  Newbie, may be, but he knows most of the constructions
>and semantic principles to look for; most of it is learning the syntax.

I claim to be able to program (Java/Python), but would be absolutely lost 
programming in Lisp. It is more than just "learning the syntax", it includes a 
thought paradigm as well.

Just like I claim to be able to do math, but severely suck at RPN math. (Okay, 
that analogy is bad but it is all I can come up with at the moment.)

Ramit



Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423


-Original Message-
From: python-list-bounces+ramit.prasad=jpmchase@python.org 
[mailto:python-list-bounces+ramit.prasad=jpmchase@python.org] On Behalf Of 
Hans Georg Schaathun
Sent: Wednesday, May 11, 2011 1:06 PM
To: python-list@python.org
Subject: Re: checking if a list is empty

On 11 May 2011 16:26:40 GMT, Steven D'Aprano
   wrote:
: > 1. My concern was not about clueless newbies.  They need to
: >   learn.  My concern is about experienced scientists and engineers who
: >   are simply new to python.
: 
:  Which makes them clueless newbies *about Python*. I don't care how 
:  experienced they are in astrophysics or biology or calculating the 
:  average airspeed of an unladen swallow.

:  Yeah, life is hard and then you die, and scientists don't even get paid 
:  that much. So what? Do physicists write their scientific papers about 
:  string theory with the thought "What if some Python programmer who knows 
:  nothing about string theory is reading this? I better dumb it down."

That depends on the purpose of that particular paper, but the real 
question is, who writes the software to test that string theory 
empirically?  Please tell.

-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list
This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On Wed, 11 May 2011 14:59:34 -0400, Prasad, Ramit
   wrote:
:  Fair enough. I am a sheep, so I do what other (more knowledgeable)
: people do. It is a fair assumption (for my specific code writing 
: environments) that everyone who is going to read my code understands 
: "if x:" notation or is expected to learn enough Python to understand it.

That's fair enough.  You know your code, so it is probably true.
It would not be true for the code I am writing.

-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On Wed, 11 May 2011 12:17:33 -0700, Ethan Furman
   wrote:
:  'if li' *is* KISS.

It /might/ be in some contexts, but a priori it is not, as it
superimposes a truth value on a data type which is otherwise
a pretty accurate model of real objects (outside python).

One principle of object oriented programming is to bestow the
objects with properties reflecting known properties from the
domain being modelled.  Lists do not have truth values in the
application domain, and therefore truth values in the
implementation domain is complicated.

-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On Wed, 11 May 2011 14:44:37 -0400, Prasad, Ramit
   wrote:
: > Someone who knows how to program is never clueless starting a new
: >language.  Newbie, may be, but he knows most of the constructions
: >and semantic principles to look for; most of it is learning the syntax.
: 
:  I claim to be able to program (Java/Python), but would be absolutely
: lost programming in Lisp. It is more than just "learning the syntax",
: it includes a thought paradigm as well.

OK.  I should written 'how to program imperatively' ... 'new imperative
language'.  Or substitute functional/logical/whatever for imperative.

You would not be completely clueless moving to
ada/fortran/C/pascal/simula.  There may be new concepts,
and some concepts which must be adapted to another level of
abstraction, but you do have a clue about the core concepts.

-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Ian

On 11/05/2011 20:13, Hans Georg Schaathun wrote:

On Wed, 11 May 2011 12:17:33 -0700, Ethan Furman
 wrote:
:  'if li' *is* KISS.

It /might/ be in some contexts, but a priori it is not, as it
superimposes a truth value on a data type which is otherwise
a pretty accurate model of real objects (outside python).

One principle of object oriented programming is to bestow the
objects with properties reflecting known properties from the
domain being modelled.  Lists do not have truth values in the
application domain, and therefore truth values in the
implementation domain is complicated.

Exactly. Its just a convention.  If it exists, its true, if if doesn't 
its false.


In the "real world"  lists of zero items do not exist.
You don't go shopping with a shopping list of zero items.
You don't take a journey going nowhere.
You wouldn't have a party and invite nobody.
What kind of building is one with zero floors?
Would you have an Aircraft Carrier with no aircraft?

Oh Wait - the UK has one of those coming into service soon.

Regards

Ian





--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread harrismh777

Hans Georg Schaathun wrote:

Code is quite often published to document algorithms, methods and
formulæ for the purpose of scientific research.  Since there is no
universal language which suits everything and everyone, this
is exactly what happens.  One has to have the rudimentary knowledge
to read half a dozen different languages to be able to read the
code and extract the algorithms.


+1  QOTW





--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread harrismh777

D'Arcy J.M. Cain wrote:

Non-programmers should be able to program?

Should non-doctors be able to doctor?  Should cars be built so that
anyone can intuitively fix them without a mechanic?


   Non-programmers should not be expected to program in 'C' nor in lisp...

   ... but non-programmers were able to program in BASIC jes fine...


I contend that non-programmers are able to learn rudimentary python and 
work with it to solve real problems 'without' formal training in 
'programming'.


Python is the New BASIC for 'people'. At least, it has the potential to 
be that...   people should be able to talk to their computers (whatever 
we mean by that) and have the computer respond with real-world 
solutions.  We need to move away from 'canned apps' to a new day where 
the masses can sit down to their computer and solve new problems with it 
through intuitive language skills.  Why not?


--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Steven D'Aprano
On Wed, 11 May 2011 19:05:03 +, Chris Torek wrote:

> In article <4dcab8bf$0$29980$c3e8da3$54964...@news.astraweb.com> Steven
> D'Aprano   wrote:
>>When you call len(x) you don't care about the details of how to
>>calculate the length of x. The object itself knows so that you don't
>>have to. The same applies to truth testing.
>>
>>I have a data type that is an array of lists. When you call "if len(x) >
>>0" on it, it will blow up in your face, because len(x) returns a list of
>>lengths like [12, 0, 2, 5]. But if you say "if x", it will do the right
>>thing. You don't need to care how to truth-test my data type, because it
>>does it for you. By ignoring my type's interface, and insisting on doing
>>the truth-test by hand, you shoot yourself in the foot.
> 
> What this really points out is that "if x" and "if len(x) > 0" are
> *different tests*.

*Potentially* different tests. Which is exactly the point. Given an 
arbitrary object, the developer doesn't know what test is appropriate. 
Should I write len(x) == 0 or list(x) == [] or x.next is None or 
something else? How can I tell which is appropriate without knowing 
everything about the internals of every object I ever see?

But if x is a non-broken object, then you don't have to. Just test on x 
itself, because it knows what to do to be considered a truth value.

Of course there may be objects where this doesn't work. There are no 
guarantees in Python. You can't even guarantee that printing an object 
won't blow up:

>>> class Broken:
...  def __str__(self):
...  return "... %s ..." % 1/2
...  __repr__ = __str__
...
>>> b = Broken()
>>> b
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 3, in __str__
TypeError: unsupported operand type(s) for /: 'str' and 'int'


> Consider xml.etree.ElementTree "Element" objects.
> The documentation says, in part:
> 
> In ElementTree 1.2 and earlier, the sequence behavior means that an
> element without any subelements tests as false (since it's an empty
> sequence), even if it contains text and attributions. ...
> 
> Note: This behavior is likely to change somewhat in ElementTree 1.3.
>  To write code that is compatible in both directions, use ...
> "len(element)" to test for non-empty elements.
> 
> In this case, when x is an Element, the result of bool(x) *could* mean
> just "x has sub-elements", but it could also/instead mean "x has
> sub-elements, text, or attributions".

Either behaviour is correct, but a semantic change to the class means 
that you have to do more work if you care about supporting both versions 
in the same code base. That is a neat example of where you might choose 
*not* to let an object decide for itself whether it is true or false, but 
instead impose your own definition on it.




-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Steven D'Aprano
On Wed, 11 May 2011 20:13:35 +0100, Hans Georg Schaathun wrote:

> One principle of object oriented programming is to bestow the objects
> with properties reflecting known properties from the domain being
> modelled.  Lists do not have truth values in the application domain

Yes they do. Empty lists are nothing, ergo false, and non-empty lists are 
something, ergo true.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Steven Howe

On 05/11/2011 02:47 PM, Steven D'Aprano wrote:

On Wed, 11 May 2011 20:13:35 +0100, Hans Georg Schaathun wrote:


One principle of object oriented programming is to bestow the objects
with properties reflecting known properties from the domain being
modelled.  Lists do not have truth values in the application domain

Yes they do. Empty lists are nothing, ergo false, and non-empty lists are
something, ergo true.


>>>  a=[]
>>>  if a:
... print 'Yes'
...
>>>  a=[1]
>>>  if a:
... print 'Yes'
...
Yes


Cool; I'd never of thought to try that method to determine if a list was 
empty. I usually test it's length.

This looks faster.


--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread harrismh777

Steven D'Aprano wrote:

modelled.  Lists do not have truth values in the application domain

Yes they do. Empty lists are nothing, ergo false, and non-empty lists are
something, ergo true.



No they don't.  Empty lists are empty lists... which just happen to 
become False when type cast  bool(list[])--> False.


lists cannot have a truth... binary False or True... however, when cast 
with bool(list) they can be used in a test (even with 'not') to make 
some decision.


Lists by themselves, empty or not, cannot have a 'truth' in an of 
themselves.



kind regards,
m harris

--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Gregory Ewing

Hans Georg Schaathun wrote:

 0 is a number as real and existent as any other,
one would think that the empty list is also as real and existent as
any other list.


0 does have some special properties, though, such as
being the additive identity and not having a multiplicative
inverse. Adding falseness as another special property isn't
too much of a stretch and turns out to be useful.

Likewise, it's useful to treat empty containers as having
a similar special property, since they're often a base or
terminating case in algorithms.

It's especially useful in a dynamic language where any
additional operations such as finding the length or
comparing with zero has a run-time cost.

Yes, you have to learn it, but it's a small thing to
learn with a considerable payoff.

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread harrismh777

harrismh777 wrote:

Lists by themselves, empty or not, cannot have a 'truth' in an of
themselves.


   ... forgot.,


   Based on Ian's comment a couple of days ago...

   if alist:


 ... is actually :


   if bool(alist):


   I think this is more than just semantics or silly argumentation. Its 
important to understand where the boolean truth is coming from...  my 
understanding 'now' is that the  list[] has no such boolean attribute, 
but is cast for the 'if' construct



so...if alist:is   -->  if bool(alist):

and...   if not alist:is also  -->  if not bool(alist):


   The 'alist[]' has no boolean attribute,   right??


kind regards,

m harris



--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Steven D'Aprano
On Wed, 11 May 2011 17:38:58 -0500, harrismh777 wrote:

> Steven D'Aprano wrote:
>>> modelled.  Lists do not have truth values in the application domain
>> Yes they do. Empty lists are nothing, ergo false, and non-empty lists
>> are something, ergo true.
>>
>>
> No they don't.  Empty lists are empty lists... which just happen to
> become False when type cast  bool(list[])--> False.
> 
> lists cannot have a truth... binary False or True... however, when cast
> with bool(list) they can be used in a test (even with 'not') to make
> some decision.


Have you been not paying any attention at all?


>>> alist = []
>>> if alist: pass
... else: print "alist is a false value"
...
alist is a false value
>>>
>>> if type(alist) is bool: pass
... else: print "but not a bool"
...
but not a bool



> Lists by themselves, empty or not, cannot have a 'truth' in an of
> themselves.

Despite your confident tone, they really do. Just like EVERY OTHER OBJECT 
IN PYTHON. And Perl, and Ruby, and Javascript, and PHP, and many other 
languages. You might not like that fact, but it is a fact.



-- 
Steven

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread alex23
Hans Georg Schaathun  wrote:
> Revolutionary indeed, so why don't we exploit the revolution
> and write the programs to be as accessible as possible?

Where do you draw the line, though?

No decorators, as they're not intuitively obvious? No custom
descriptors, as that requires a deeper knowledge of Python internals
that utter ignorance allows?

Both of those aspects alone seem far more complex and advanced than
treating empty collections as False.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread alex23
On May 12, 7:24 am, harrismh777  wrote:
> We need to move away from 'canned apps' to a new day where
> the masses can sit down to their computer and solve new problems with it
> through intuitive language skills.  Why not?

Because the vast majority of them don't seem to want to be bothered?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Chris Torek
In article <4dc6a39a$0$29991$c3e8da3$54964...@news.astraweb.com>
Steven D'Aprano   wrote:
>In English, [the word "not"] negates a word or statement:
>
>"the cat is not on the mat" --> "the cat is on the mat" is false.

As a mostly off topic aside, English is considerably more complicated
than that.  There are people who use the word "not" as a purely
boolean operator (a la computer languages), so that "the cat is
not not on the mat" means "the cat IS on the mat", but others use
double negation as a form of intensifier, so that the phrase with
multiple "not"s is simply a more emphatic claim: the cat is really,
truly, *definitely*, not on that particular mat. :-)

In various other "natural languages" -- i.e., languages meant for
human-to-human communications, rather than for computers -- multiple
negatives are more often (or always?) intensifiers.  Some languages
have the idea of "negative matching" in much the same sense that
English has number [%] matching: "the cat is on the mat" and "the cats
are on the mat" are OK because the noun and verb numbers match,
but neither "the cats is on the mat" nor "the cat are on the mat"
are correct.

[% "Number" here is really 1 vs not-1: no cats, one cat, two cats.]

Of course, there are descriptivists and prescriptivists, and many
of the latter claim that using multi-valued boolean logic in English
is "nonstandard" or "invalid".  Many of those in turn will tell
you that "ain't good English" ain't good English.  Still, one should
be aware of these forms and their uses, in much the same way as
one should be able to boldly split infinitives. :-)

Moving back towards on-topic-ness:

>As an operator, "not" negates a true value to a false value. In 
>mathematical Boolean algebra, there only is one true value and one false 
>value, conventionally called True/False or 1/0. In non-Boolean algebras, 
>you can define other values. In three-value logic, the negation of True/
>False/Maybe is usually False/True/Maybe. In fuzzy logic, the logic values 
>are the uncountable infinity (that's a technical term, not hyperbole) of 
>real numbers between 0 and 1.

Or, to put it another way, before we can communicate clearly, we have
to pick out a set of rules.  Most computer languages do this pretty
well, and Python does a good (and reasonably conventional) job:

>Python uses a boolean algebra where there are many ways of spelling the 
>true and false values. The "not" operator returns the canonical bool 
>values:
>
>not  returns False
>not  returns True
>
>Take note of the distinction between lower-case true/false, which are 
>adjectives, and True/False, which are objects of class bool.

(At least as of current versions of Python -- in much older versions
there was no real distinction between booleans and type "int",
presumably a a holdover from C.)

[remainder snipped as I have nothing else to add]
-- 
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)  http://web.torek.net/torek/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Chris Angelico
On Thu, May 12, 2011 at 7:02 AM, Ian  wrote:
> In the "real world"  lists of zero items do not exist.
> You don't go shopping with a shopping list of zero items.

Actually, yes you do. You maintain your shopping list between trips;
whenever you need something, you put it on the list immediately. Then
when you go shopping, you just take the list with you (if you're
lucky, you don't need to move or copy it at all, you just get another
reference to it). Once you're done, you empty the list - you now have
a shopping list with zero items (until you get home and realize you
forgot something).

Chris Angelico
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread harrismh777

alex23 wrote:

through intuitive language skills.  Why not?

Because the vast majority of them don't seem to want to be bothered?



That could very well be... but I have a hope for them. I honestly think 
its not because they don't want to be bothered, rather they just think 
its too far past them...   and not do-able.


This is where I think it would be helpful at the undergraduate level to 
insist that *all* students learn some programming (and yes, using 
Python). Actually, I am thinking that it would be great to begin this in 
grade school. But then, I'm also one of those Americans who believe that 
every student should learn at least (1) non-English language beginning 
in 1st grade--- mandatory.(of course others are just hoping 
they learn English...)






kind regards,
m harris

--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Gregory Ewing

Roy Smith wrote:

Hans Georg Schaathun  wrote:
If both are numbers, they are converted to a common type. Otherwise, 
objects of different types always compare unequal


That's just the default treatment for unrelated types that don't
know anything about each other.

I would guess that the list's == method is asking "Is the
other object a list?", and since a subclass of list is also
a list, it's happy and goes on to compare the elements.

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread D'Arcy J.M. Cain
On Wed, 11 May 2011 16:24:47 -0500
harrismh777  wrote:
> D'Arcy J.M. Cain wrote:
> Non-programmers should not be expected to program in 'C' nor in lisp...
> 
> ... but non-programmers were able to program in BASIC jes fine...

They still had to learn the language.

> I contend that non-programmers are able to learn rudimentary python and 
> work with it to solve real problems 'without' formal training in 
> 'programming'.

When did the discussion shift from "learn the language" to "formal
training?"  How you learn the language is totally irrelevant.

> Python is the New BASIC for 'people'. At least, it has the potential to 
> be that...   people should be able to talk to their computers (whatever 
> we mean by that) and have the computer respond with real-world 
> solutions.  We need to move away from 'canned apps' to a new day where 
> the masses can sit down to their computer and solve new problems with it 
> through intuitive language skills.  Why not?

That's not programming.  That's using a canned app that a programmer
wrote that takes your unstructured input and does something useful with
it.  Spreadsheets are a primitive example of that.  Google is a more
advanced example.

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On 11 May 2011 21:47:27 GMT, Steven D'Aprano
   wrote:
:  On Wed, 11 May 2011 20:13:35 +0100, Hans Georg Schaathun wrote:
: > One principle of object oriented programming is to bestow the objects
: > with properties reflecting known properties from the domain being
: > modelled.  Lists do not have truth values in the application domain
: 
:  Yes they do. Empty lists are nothing, ergo false, and non-empty lists are 
:  something, ergo true.

What application domain has established that terminology?

-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On Wed, 11 May 2011 20:16:01 -0700 (PDT), alex23
   wrote:
:  Hans Georg Schaathun  wrote:
: > Revolutionary indeed, so why don't we exploit the revolution
: > and write the programs to be as accessible as possible?
: 
:  Where do you draw the line, though?

I said that, "as possible".  You draw it at the limit of possibility.

:  No decorators, as they're not intuitively obvious? No custom
:  descriptors, as that requires a deeper knowledge of Python internals
:  that utter ignorance allows?

When they help clarify or simplify the code, they are good.
When they do nothing of the sort, they aren't.

:  Both of those aspects alone seem far more complex and advanced than
:  treating empty collections as False.

Probably, but they also seem far more useful.

-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On Thu, 12 May 2011 17:44:07 +1200, Gregory Ewing
   wrote:
:  Roy Smith wrote:
: > Hans Georg Schaathun  wrote:
: >>If both are numbers, they are converted to a common type. Otherwise, 
: >>objects of different types always compare unequal

Actually, I did not.
:-- hg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Steven D'Aprano
On Wed, 11 May 2011 22:53:45 -0500, harrismh777 wrote:

> alex23 wrote:
>>> through intuitive language skills.  Why not?
>> Because the vast majority of them don't seem to want to be bothered?
>>
>>
> That could very well be... but I have a hope for them. I honestly think
> its not because they don't want to be bothered, rather they just think
> its too far past them...   and not do-able.

An admirable hope, but there is a significant amount of research into 
teaching computer programming that suggests that learning to program is 
simply beyond a large portion of the population, no matter what you do or 
what language you teach. Some 30-60% of people barely get past "Hello 
World".

(That's not to imply that they're dumb, just that whatever mental skills 
are needed for programming is beyond them, just as whatever mental skills 
are needed for writing poetry are beyond me.)

http://www.codinghorror.com/blog/2006/07/separating-programming-sheep-from-non-programming-goats.html

Shorter version: it seems that programming aptitude is a bimodal 
distribution, with very little migration from the "can't program" hump 
into the "can program" hump. There does seem to be a simple predictor for 
which hump you fall into: those who intuitively develop a consistent 
model of assignment (right or wrong, it doesn't matter, so long as it is 
consistent) can learn to program. Those who don't, can't.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On Thu, 12 May 2011 01:49:05 -0400, D'Arcy J.M. Cain
   wrote:
:  That's not programming.  That's using a canned app that a programmer
:  wrote that takes your unstructured input and does something useful with
:  it.  Spreadsheets are a primitive example of that.  Google is a more
:  advanced example.

You are really trying to defend the programmers' status as a modern
day priesthood, mastering a mystic art completely inaccessible to
those not initiated.  

For ages, the literate elite deliberately made the language cryptic
to protect their art and their status.  Some programmers seem to do
the same.

The fact is that it is not black and white.  There are programmers
with domain expertise, programmers without domain expertise, 
domain experts with decent programming skills, domain experts with
rudimentary programming skills, monolingual programmers, domain
experts without programming skills, polyglot programmers etc.

Only very narrow-purpose applications can be created by one of
these groups on their own, and to collaborate their abilities
must be overlapping.

-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On 11 May 2011 21:42:10 GMT, Steven D'Aprano
   wrote:
:  *Potentially* different tests. Which is exactly the point. Given an 
:  arbitrary object, the developer doesn't know what test is appropriate. 
:  Should I write len(x) == 0 or list(x) == [] or x.next is None or 
:  something else? How can I tell which is appropriate without knowing 
:  everything about the internals of every object I ever see?

Sure, but the question asked was how to check if a /list/ is empty.
You defend your answer assuming a different question.  You could
at least have the decency to change the subject header when you
go down that route.


-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Hans Georg Schaathun
On Wed, 11 May 2011 20:31:45 -0700 (PDT), alex23
   wrote:
:  On May 12, 7:24 am, harrismh777  wrote:
: > We need to move away from 'canned apps' to a new day where
: > the masses can sit down to their computer and solve new problems with it
: > through intuitive language skills.  Why not?
: 
:  Because the vast majority of them don't seem to want to be bothered?

Why does that matter?  There is a sizeable group who need computers
for purposes not (sufficiently) supported by the `canned apps'.
The fact that they are outnumbered by users who really only need
typewriters and entertainment theatres does in no way reduce the
need of those who actually need /computers/.

-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-12 Thread Ben Finney
Hans Georg Schaathun  writes:

> On Wed, 11 May 2011 20:31:45 -0700 (PDT), alex23
>wrote:
> :  On May 12, 7:24 am, harrismh777  wrote:
> : > We need to move away from 'canned apps' to a new day where
> : > the masses can sit down to their computer and solve new problems with it
> : > through intuitive language skills.  Why not?
> : 
> :  Because the vast majority of them don't seem to want to be bothered?
>
> Why does that matter?  There is a sizeable group who need computers
> for purposes not (sufficiently) supported by the `canned apps'.

Those people, outnumbered by the masses as you say, are thereby not
themselves “the masses”.

-- 
 \  “Hey Homer! You're late for English!” “Pff! English, who needs |
  `\  that? I'm never going to England!” —Barney & Homer, _The |
_o__)Simpsons_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-12 Thread Hans Georg Schaathun
On Thu, 12 May 2011 16:46:38 +1000, Ben Finney
   wrote:
:  Hans Georg Schaathun  writes:
: 
: > On Wed, 11 May 2011 20:31:45 -0700 (PDT), alex23
: >wrote:
: > :  On May 12, 7:24 am, harrismh777  wrote:
: > : > We need to move away from 'canned apps' to a new day where
: > : > the masses can sit down to their computer and solve new problems with it
: > : > through intuitive language skills.  Why not?
: > : 
: > :  Because the vast majority of them don't seem to want to be bothered?
:  >
: > Why does that matter?  There is a sizeable group who need computers
: > for purposes not (sufficiently) supported by the `canned apps'.
: 
:  Those people, outnumbered by the masses as you say, are thereby not
:  themselves “the masses”.

So what?  Do we only need solutions and systems for the masses?

What about systems for those who develop systems for the masses?
Or the theory necessary to develop the systems to develop more
advanced systems for the masses in the future?

Get real, software development and programming is more than just
overpriced web systems that just almost manage to replicate the 
functionality of IBM page based terminals and mainframes of 1973,
just slower and with more eye candy.

-- 
:-- Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-12 Thread Ben Finney
Hans Georg Schaathun  writes:

> On Thu, 12 May 2011 16:46:38 +1000, Ben Finney
>wrote:
> :  Hans Georg Schaathun  writes:
> : 
> : > On Wed, 11 May 2011 20:31:45 -0700 (PDT), alex23
> : >wrote:
> : > :  On May 12, 7:24 am, harrismh777  wrote:
> : > : > We need to move away from 'canned apps' to a new day where
> : > : > the masses can sit down to their computer and solve new problems with 
> it
> : > : > through intuitive language skills.  Why not?
> : > : 
> : > :  Because the vast majority of them don't seem to want to be bothered?
> :  >
> : > Why does that matter?  There is a sizeable group who need computers
> : > for purposes not (sufficiently) supported by the `canned apps'.
> : 
> :  Those people, outnumbered by the masses as you say, are thereby not
> :  themselves “the masses”.
>
> So what?  Do we only need solutions and systems for the masses?

Your “why does that matter?” was addressed to an answer specifically in
the context of “a new day where the masses can sit down to their
computer and …”. The question is asked and answered.

If you want to raise a *new* topic – that of the non-masses who have
different needs – it's best not to start with “Why does that matter?”
but to lay out your separate case.

-- 
 \“Visitors are expected to complain at the office between the |
  `\ hours of 9 and 11 a.m. daily.” —hotel, Athens |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >