Beranda > Python > [Python] Comparing NaN, Inf, None, 0, 1,…

[Python] Comparing NaN, Inf, None, 0, 1,…

What is the result of this code snippet:

my_list = [1, 2, 3, 9, 1]
my_list.sort()

Yes, you are right, the result will be like this:

[1, 1, 2, 3, 9]

Hmm, that’s easy. What’s about if you’re asked which is bigger of None and NaN? Or True and NotImplemented? Or Ellipsis (What the hell is this Ellipsis?).
Just try it:

my_weird_list = [True, False, 0, -1, 1, 100, float('nan'), float('inf'), -float('inf'), NotImplemented, Ellipsis, None]
print my_weird_list.sort()

What will be the output? If your answer is None, you are right because sort() method return None #Kidding🙂

Let’s print the my_weird_list. And, here we go :

[None, -inf, -1, False, 0, True, 1, 100, nan, inf, NotImplemented, Ellipsis]

For your note, int(True) == 1, so 1 and True is the same value when you compared them.

The good thing (for me at least), None is less than anything, even -inf. And, there is bigger value than inf.🙂

The other thing is, the position of nan in the sorted list. If you compare nan with anything it always give False. Even when nan == nan. It will return True if you use != operator.

 

So, it’s true that False is bigger (better?) than None or nothing.

Kategori:Python Tag:,
  1. Belum ada komentar.
  1. No trackbacks yet.

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

%d blogger menyukai ini: