473,890 Members | 1,769 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

returning True, False or None

I have lists containing values that are all either True, False or None,
e.g.:

[True, None, None, False]
[None, False, False, None ]
[False, True, True, True ]
etc.

For a given list:
* If all values are None, the function should return None.
* If at least one value is True, the function should return True.
* Otherwise, the function should return False.

Right now, my code looks like:

if True in lst:
return True
elif False in lst:
return False
else:
return None

This has a light code smell for me though -- can anyone see a simpler
way of writing this?

STeVe
Jul 18 '05
35 3410
Brian van den Broek <bv****@po-box.mcgill.ca> wrote:
...
* If all values are None, the function should return None.
* If at least one value is True, the function should return True.
* Otherwise, the function should return False.
... for val in (x for x in lst if x is not None):
return val
return None
... These don't do what the OP desired.


Ah, you're right, True should take precedence, point 2 of the specs.
OK, let's take advantage of the fact that None < False < True:

return max(lst)
This fails when lst is empty (the specs presumably imply a None should
be returned then). More robust:

return max(lst or [None])
Alex
Jul 18 '05 #31
Christos TZOTZIOY Georgiou wrote:
On Fri, 04 Feb 2005 13:04:16 -0500, rumours say that Steve Holden
<st***@holdenwe b.com> might have written:

[STeVe]
For a given list:
* If all values are None, the function should return None.
* If at least one value is True, the function should return True.
* Otherwise, the function should return False.

[Stevbe]
If you wanted to get clever you could write something like

for i in True, False:
if i in lst:
return i
return False

[!Steve]

You mistyped None as False in the last line. Your typos are getting worse every
day :)


That wasn't a *type*, it was a *thinko*

regards
Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005 http://www.pycon.org/
Steve Holden http://www.holdenweb.com/
Jul 18 '05 #32
Steve Holden wrote:
Christos TZOTZIOY Georgiou wrote:
On Fri, 04 Feb 2005 13:04:16 -0500, rumours say that Steve Holden
<st***@holdenwe b.com> might have written:

[STeVe]
For a given list:
* If all values are None, the function should return None.
* If at least one value is True, the function should return True.
* Otherwise, the function should return False.


[Stevbe]
If you wanted to get clever you could write something like

for i in True, False:
if i in lst:
return i
return False


[!Steve]

You mistyped None as False in the last line. Your typos are getting
worse every
day :)

That wasn't a *type*, it was a *thinko*

regards
Steve


Sheesh, now I even make typos typing about typos ...

giving-up-on-the-spill-chocker-ly y'rs - steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005 http://www.pycon.org/
Steve Holden http://www.holdenweb.com/
Jul 18 '05 #33
I think it is evil to do something "at your own risk" ; I will certainly not
embark some roller coaster at my own risk.

I also think it is evil to scan the whole list (as "max" ought to do) when
only scanning the first few elements would suffice most of the time.

Regards

Francis Girard

Le vendredi 4 Février 2005 21:13, Steven Bethard a écrit*:
Fredrik Lundh wrote:
Steven Bethard wrote:
Raymond Hettinger wrote:
return max(lst)

Very clever! Thanks!


too clever. boolean > None isn't guaranteed by the language
specification:


Yup. I thought about mentioning that for anyone who wasn't involved in
the previous thread discussing this behavior, but I was too lazy. ;)
Thanks for pointing it out again.

This implementation detail was added in Python 2.1a1, with the following
note[1]:

"The outcome of comparing non-numeric objects of different types is
not defined by the language, other than that it's arbitrary but
consistent (see the Reference Manual). An implementation detail changed
in 2.1a1 such that None now compares less than any other object. Code
relying on this new behavior (like code that relied on the previous
behavior) does so at its own risk."

Steve

[1] http://www.python.org/2.1/NEWS.txt


Jul 18 '05 #34
nghoffma wrote:
sorry, that should have been:

py>>import sets
py>>def doit(thelist):
... s = sets.Set(thelis t)
... if s == sets.Set([None]):
... return None
... else:
... return max(s - sets.Set([None]))


Since a function that doesn't return is equivalent to one that returns
None, you can write it as:
def doit(lst):

.... s = set(lst) - set([None])
.... if s: return max(s)

that looks to me as the most elegant so far, but this is just because
it's mine :-)

You can also filter out Nones with a list/generator comprehension, but
sets are just more elegant...

--
Ciao,
Matteo
Jul 18 '05 #35
Matteo Dell'Amico wrote:
Since a function that doesn't return is equivalent to one that returns
None, you can write it as:
>>> def doit(lst):

... s = set(lst) - set([None])
... if s: return max(s)

that looks to me as the most elegant so far, but this is just because
it's mine :-)


Cool. I prefer to be explicit about returns (e.g. not counting on the
automatic return None), and I'd rather not create the unnecessary None
set, so I would probably write this like:

py> def f(lst):
.... s = set(lst)
.... s.discard(None)
.... if s:
.... return max(s)
.... else:
.... return None
....

But it's definitely a very elegant solution. Thanks!

Steve
Jul 18 '05 #36

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
7132
by: M-a-S | last post by:
Can anybody explain this: Python 2.3 (#46, Jul 29 2003, 18:54:32) on win32 Type "help", "copyright", "credits" or "license" for more information. >>> >>> None = 3 <stdin>:1: SyntaxWarning: assignment to None >>> False = 4 >>> True = 5 >>>
46
4278
by: Scott Chapman | last post by:
There seems to be an inconsistency here: Python 2.3.2 (#1, Oct 3 2003, 19:04:58) on linux2 >>> 1 == True True >>> 3 == True False >>> if 1: print "true" ....
2
1582
by: Rodney Maxwell | last post by:
In Python 2.4.1: >>> None = 99 SyntaxError: assignment to None >>> True = 99 >>> False = 99 >>> True == False True ----------------------- So why is 'None' special?
10
2448
by: randomtalk | last post by:
hello, i have another problem i feel that i have to be missing something.. Basically, i've written a recursive function to find all the prime up to a number (lim).. here is the function: The function basically takes in a list of all the prime number found, it takes the next number to be tested for (next) and the limit it will go up to. It divide next by the list of previous prime numbers if next is not bigger than lim, count up all the...
3
6954
by: Thirsty Traveler | last post by:
I have a gridview where the datasource is bound after a selection. The result of doing this is that sorting and paging do not work. I was given a sample of how to resolve this, however my attempt to explicity enable sorting failes because, unlike the sample, my sort event has a null in the datasource and I am unsure why this is so. Sample HTML code is: <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"...
90
3509
by: John Salerno | last post by:
I'm a little confused. Why doesn't s evaluate to True in the first part, but it does in the second? Is the first statement something different? False print 'hi' hi Thanks.
13
2270
by: agent-s | last post by:
I have a function, generally described as so: def function(args): if condition: if condition2: function(args+1) elif condition3: print "text" return True else:
0
4110
by: cyberdawg999 | last post by:
Greetings all in ASP land I have overcome one obstacle that took me 2 weeks to overcome and I did it!!!!! I am so elated!! thank you to all who invested their time and energy towards helping me with my problems. Now for my new little problem,I had a problem posting the values from checkbox fields to a database and thats the obstacle I overcame. Now the second part is my new problem is that I want that the next time that page loads for...
12
18358
by: Karlo Lozovina | last post by:
I'm not sure if Python can do this, and I can't find it on the web. So, here it goes: try: some_function() except SomeException: some_function2() some_function3() ...
0
9976
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9815
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11215
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10801
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10904
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10449
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9616
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6034
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4258
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.