A story that stumbled upon a comparison operation

When I tried to reduce the amount of code by writing a little bit and using the comparison operator, I stumbled in an unexpected place, so I will leave it as a memorandum.

environment

Target audience

myself

Operator list

Python has the following comparison operators, which are used for conditional statements such as branching.

operator result
x < y True if x is less than y
x <= y True if x is less than or equal to y
x > y True if x is greater than y
x >= y True if x is greater than or equal to y
x == y True if the values of x and y are equal
x != y True if x and y values are not equal
x is y True if x and y are the same object
x is not y True if x and y are not the same object
x in y True if x is contained in y
x not in y True if x is not included in y

There are other logical operators such as the following, and it is possible to create conditional statements with a high degree of freedom by combining these.

operator result
x and y Returns y when x is True and y is also True. Returns x when x is False
x or y Returns x when x is True. Returns y when x is False
not x Returns False if x is True, True if x is False

How to check if the result of a logical operator is valid

In the case of ʻand or ʻor, it is important whether the left side is True or False. You can easily check this with bool.

bool Of course, True and False will return the same result.

>>> bool(True)
True
>>> bool(False)
False

Numerical value

In the case of numeric type, True is returned except for 0.

>>> bool(1)
True
>>> bool(0)
False
>>> bool(-1)
True
>>> bool(0.5)
True
>>> bool(1j)
True
>>> bool(0j)
False
>>> bool(-1j)
True

String

The string type is True if the character is present.

>>> bool('')
False
>>> bool('hoge')
True
>>> bool(' ')
True

Note that this is not looking if a ** instance of str has been created **.

>>> type('')
<class 'str'>

None None is also treated as False.

>>> bool(None)
False

Array

The array returns True when there is one or more elements.

>>> bool([])
False
>>> bool([""])
True
>>> bool([None])
True

Stumble point

As we've seen, it's pretty easy, but the caveat is that ** elements don't always return True when they exist **.

Before explaining what it means, I have summarized the conditions for becoming False below.

>>> bool(False)
False
>>> bool(0)
False
>>> bool('')
False
>>> bool(None)
False
>>> bool([])
False

As far as I can see this, if there is no content, it is likely to be False.

So I ran the following code.

>>> import numpy as np
>>> hoge = None
>>> fuga = True
>>> if fuga:
...     hoge = np.arange(10)
>>> bazz = hoge if hoge else list(range(10))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

** Rainy day error! ** ** What I personally wanted to do is that there is a function that generates an ndarray when the conditional expression (fuga) is True, and another function determines whether hoge is generated and either regenerates it or leaves it as it is. I wanted to use it.

As a solution, I used None as a criterion instead of checking if an instance was created.

>>> import numpy as np
>>> hoge = None
>>> fuga = True
>>> if fuga:
...     hoge = np.arange(10)
>>> bazz = hoge if hoge is not None else list(range(10))
>>> bazz
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

However, in this case, hoge is returned even if something other than ndarray is generated in hoge, so if you want to limit it to ndarray, you need to consider it ...

Postscript (2020/3/10)

There is a built-in function called ʻis instance` as a way to check if the contents of hoge are ndarray, so you can check by using it.

>>> hoge = np.arange(10)
>>> hoge
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>>
>>> isinstance(hoge, np.ndarray)
True
>>>
>>> hoge = None
>>> fuga = True
>>> if fuga:
...     hoge = np.arange(10)
...
>>>
>>> bazz = hoge if isinstance(hoge, np.ndarray) else list(range(10))
>>> bazz
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>>
>>> bazz = hoge if isinstance(hoge, list) else list(range(10))
>>> bazz
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Chat

I was surprised that False was returned when judging the external library by bool. Well, I'm not good at trying to write strangely ... I am keenly aware that I do not have enough knowledge to master it, but I want to devote myself every day without being discouraged (・ ∀ ・)

reference

How to write conditional branch by if statement in Python

Recommended Posts

A story that stumbled upon a comparison operation
A story that stumbled upon installing matplotlib
A story that reduces the effort of operation / maintenance
A story that stumbled when using pip in a proxy environment
The story of making a package that speeds up the operation of Juman (Juman ++) & KNP
A memo that I stumbled upon when doing a quote RT on Twitter Bot
A story that Seaborn was easy, convenient and impressed
Story that an inexperienced person made a masked solver
A story that struggled with the common set HTTP_PROXY = ~
I stumbled upon using MoviePy, so make a note
A story that I was addicted to at np.where
A story that analyzed the delivery of Nico Nama.
A story that stopped my heart after upgrading OpenStack
A story that was terrible if SELinux was properly disabled
A story that took time to understand python's argsort (memorial)
An error that stumbled upon learning YOLO on Google Colab
[Python] A story that seemed to fall into a rounding trap