[Tutor] all elements equal in tuple or list
Bob Gailer
bgailer at alum.rpi.edu
Fri Nov 19 07:45:48 CET 2004
At 07:24 PM 11/18/2004, Jacob S. wrote:
>My name's not Kent, but...
>
> >def test(vals):
> > if vals:
> > i = iter(vals)
> > first = i.next()
> > for item in i:
> > if first != item:
> > return False
> > return True
>
>The if vals: is an interesting idea... If no comparison operators are
>entered after a variable, the interpreter automatically checks to see if the
>variable returns true. So if vals returns true, then the code block beneath
>it is executed.
To be more explicit (quoting from the manual) "when expressions are used by
control flow statements, the following values are interpreted as false:
None, numeric zero of all types, empty sequences (strings, tuples and
lists), and empty mappings (dictionaries). All other values are interpreted
as true."
Whatever follows - if - is taken as an expression, evaluated, then
interpreted as stated above.
The reason for doing this is: if vals is an empty sequence, iter(vals) will
raise the StopIteration exception.
>Otherwise, the function returns True.
>All that does is check to see that vals is not an empty list. (Therefore
>returning False)
>
>Empty tuples,lists,dictionaries,strings,etc. return False ex. (),[],{},""
>If they have anything in them, they return True ex.
>(''),["hello"],{"Jacob",3},"A"
>
>Nonzero integers,floats,complex numbers,Long integers, etc. return True
>All others return True
>
>
>
>
>
>_______________________________________________
>Tutor maillist - Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
Bob Gailer
bgailer at alum.rpi.edu
303 442 2625 home
720 938 2625 cell
More information about the Tutor
mailing list