Python's and and Pythons or

Terry Reedy tjreedy at udel.edu
Thu Oct 10 03:43:15 EDT 2013


On 10/10/2013 2:45 AM, Chris Angelico wrote:
> On Thu, Oct 10, 2013 at 5:12 PM, Peter Cacioppi
> <peter.cacioppi at gmail.com> wrote:
>> I'm trying to think of a good example usage of echo-argument and. Maybe something like

>> A bit awkward, echo-argument or is more naturally useful to me then echo-argument and.
>
> first_element = some_list[0]    # Oops, may crash

some_list[0:1] always works, and sometimes is usable, but you still 
cannot index the slice.

> try:
>      first_element = some_list[0]
> except IndexError:
>      firstelement = None   # A bit verbose
>
> first_element = some_list and some_list[0]
>
> # or if you want a zero instead of an empty list:
> first_element = len(some_list) and some_list[0]
>
>
> Also, consider the case where you have a function, or None:
>
> result = func(*args,**kwargs)   # NoneType is not callable
>
> result = func and func(*args,**kwargs)

y = x and 1/x
One just has to remember that y==0 effectively means y==+-infinity ;-).

-- 
Terry Jan Reedy




More information about the Python-list mailing list