Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'if' not followed by conditional statement

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?

like image 953
11thHeaven Avatar asked Mar 06 '16 12:03

11thHeaven


2 Answers

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:

  • strings of length >= 1 are Truthy.
  • empty strings are Falsy.
  • lists of length >= 1 are Truthy.
  • empty lists are Falsy.
  • 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.

like image 65
gtlambert Avatar answered Oct 22 '22 01:10

gtlambert


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

like image 23
krato Avatar answered Oct 22 '22 03:10

krato