My colleague uses this way in conditions
if len(A) is not 0:
print('A is not empty')
I prefer this one
if A:
print('A is not empty')
What is prop-cons arguments?
Her point is that first way is more straight-forward way to show what she exactly wants. My point is that my way is shorter.
Also first way is 2 times faster then my one:
>>> import timeit
>>> timeit.timeit('len(A) is not 0', setup='A=[1,2,3]')
0.048459101999924314
>>> timeit.timeit('bool(A)', setup='A=[1,2,3]')
0.09833707799998592
But
>>> import timeit
>>> timeit.timeit('if len(A) is not 0:\n pass', setup='A=[1,2,3]')
0.06600062699999398
>>> timeit.timeit('if A:\n pass', setup='A=[1,2,3]')
0.011816206999810674
second way 6 times faster! I am confused how if
works :-)
Solution 3: Using len() And given the length of an empty list is 0 it can be used to check if a list is empty in Python.
Finding the Index of the Last Item of a Sequence To display the last number in the list, you use len(numbers) and subtract 1 from it since the first index of the list is 0 . Indexing in Python allows you to use the index -1 to obtain the last item in a list.
len(A)-1 actually is the index of the last element in list A . As in python (and almost all programming languages), array indexes start from 0, so an array with n elements has index of 0, 1, 2, ..., n-1 . Follow this answer to receive notifications. answered May 10, 2018 at 12:06. BookSword.
Python has first-class functions, so len is actually an object. Ruby, on the other hand, doesn't have first class functions. So the len function object has it's own methods that you can inspect by running dir(len) .
PEP 8 style guide is clear about it:
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
Yes: if not seq: if seq: No: if len(seq): if not len(seq):
I would argue that if A = 42, your colleague code would raise an error
object of type 'int' has no len()
while your code would just execute whatever comes after the if.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With