I\'m learning the book named Data Structures & Algorithms in Python.
On Page 12 that introduce the Logical Operators, it writes:
There is another reason -- syntactic correctness -- to use short circuit. Getting an item from a list for comparison without throwing an error on empty list condition is an important reason to use short circuiting as shown below. There are other ways to handle empty list, but such code would be more complex (more lines of code).
In this example, the application requirement is to behave differently strictly when 'bob' is the last list item. Bob is required to not be last in our list! (Because Bob is the best, that's all.)
The three lines of code shown below that have conditional expressions with the "or" in them do not throw an error.
>>> a = []
>>> a[-1] == 'bob' # is the last one 'bob'?
Traceback (most recent call last):
File "", line 1, in
IndexError: list index out of range
>>> a[-1:][0] == 'bob'
Traceback (most recent call last):
File "", line 1, in
IndexError: list index out of range
>>> len(a)
0
>>> len(a)==0 or a[-1] != "bob"
True
>>> a.append('bob')
>>> len(a)==0 or a[-1] != "bob" # the last one is bob. Act different.
False
>>> a.append('news')
>>> len(a)==0 or a[-1] != "bob"
True