Python returns False if the list is empty

In one coding example, I saw the following code fragment that returns True if the list is empty and False if not

return a == []

the reason is to avoid writing

if a:
    return False
else:
    return True

In a real example with several thousand records, is there any difference in speed that I should be aware of?

+4
source share
2 answers

If you ask which method will be faster if you put the function (hence return), I used the module timeitfor a little testing. I put each method in a function and then run the program to see which function works faster. Here is the program:

import timeit

def is_empty2():
    a = []
    if a:
        return True
    else:
        return False

def is_empty1():
    a = []
    return a == []


print("Time for method 2:")
print(timeit.timeit(is_empty2))
print("")
print("Time for method 1:")
print(timeit.timeit(is_empty1))

, . , :

method one speed(milliseconds): 0.2571859563796641
-----------------------------   ------------------
method two speed(milliseconds): 0.2679253742685615

, , , , . , , .

, Cdarke . , . . : .

+2

. . length . len of a len of [] . len , .

pythonic- return not a bool, :

return not a

# or 

return not bool(a)
+4

Source: https://habr.com/ru/post/1654254/


All Articles