简体   繁体   中英

Which one is the better way to compare numbers in Python? And why?

So if I wish to compare numbers in Python, say, to check if the number falls in the inclusive range of 2 to 100.
Which of the following method is most preferable and why?

Using comparitive operators?

if(n>=2 and n<=100):
    print("Okay")

or using range() function?

if(n in range(2,101)):
    print("Okay")

Also would your answer change if the comparison if for very large numbers?

In this case the pythonic way would be to use comparison chaining :

if 2 <= n <= 100:
    print("Okay")

The difference is tiny, but here are some comparisons (I would put this in a comment, but it is too verbose):

n = 999_999_999

%%timeit -n 100000
if 2 <= n <= 1_000_000_000:
    pass
# 85.8 ns ± 13.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%%timeit -n 100000
if 2 <= n and n <= 1_000_000_000:
    pass
# 81.3 ns ± 15.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%%timeit -n 100000
if n in range(1_000_000_000):
    pass
# 360 ns ± 29.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM