I'm going through Zed's "Learn Python The Hard Way" and I'm on ex49. I'm quite confused by the following code he gives:
def peek(word_list):
if word_list: # this gives me trouble
word = word_list[0]
return word[0]
else:
return None
The condition of the if
statement is giving me trouble, as commented. I'm not sure what this means as word_list
is an object, not a conditional statement. How can word_list
, just by itself, follow if
?
The if
statement applies the built-in bool()
function to the expression which follows. In your case, the code-block inside the if
statement only runs if bool(word_list)
is True
.
Different objects in Python evaluate to either True
or False
in a Boolean context. These objects are considered to be 'Truthy' or 'Falsy'. For example:
In [180]: bool('abc')
Out[180]: True
In [181]: bool('')
Out[181]: False
In [182]: bool([1, 2, 4])
Out[182]: True
In [183]: bool([])
Out[183]: False
In [184]: bool(None)
Out[184]: False
The above are examples of the fact that:
>= 1
are Truthy.>= 1
are Truthy.None
is Falsy.So: if word_list
will evaluate to True
if it is a non-empty list. However, if it is an empty list or None
it will evaluate to False
.
He is checking if word_list
is empty or not. If a list is empty and it is used in a conditional statement, it is evaluated to False. Otherwise, it is evaluated to True.
word_list = ['some value']
if word_list:
# list is not empty do some stuff
print "I WILL PRINT"
word_list = []
if word_list:
# list is empty
print "I WILL NOT PRINT"
In the above code, only the first snippet will print.
See the following reference: https://docs.python.org/2/library/stdtypes.html#truth-value-testing
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