Nested if statement returns nothing in list of lists
<p>Here is my list (of lists):</p>

<pre><code>mylist = [ [1, "John", None, "Doe"], [2, "Jane", "group1", "Zee"], [3, "Lex", "group2", "Fee"]]

y = 2

for sublist in mylist:
    if sublist[0] == y:   # meaning the third list
        if sublist[2] == None:
            print(sublist[2]) # this should print nothing
        else:
            print(sublist[2]) #this should print something
</code></pre>

<p>The end result is that nothing prints for this code. </p>

<p>I am trying to do a check for situations where I have a <code>None</code> value in my list (of lists). This method above doesn't seem to work.</p>

<p>I cannot figure out why it refuses to print anything at all, but I assume the nested <code>if sublist[2] == None:</code> may have something to do with it.</p>

<p>I think I understand what you are trying to accomplish.
You like to enumerate through a list of lists, then check the <code>y</code>-th field to see if it contains <code>None</code>.</p>

<p>The problem you are facing is that when you do:</p>

<pre><code>y = 2 
</code></pre>

<p>indicating the third field and later you do:</p>

<pre><code>if sublist[0] == y:
</code></pre>

<p>then you are checking if the <strong>first</strong> field (indicated by <code>[0]</code>) of the <code>sublist</code> is equal to <code>2</code></p>

<p>which brings you to the third sublist, not the third field in the sublist enumeration. This is where your code goes wrong.</p>

<p>You need to drop the <code>if sublist[0] == y:</code> completely, and simply check <code>sublist[y]</code></p>

<p>The following code will enumerate your list of lists, then check the <code>y</code>-th field for <code>None</code>:</p>

<pre><code>mylist = [ [1, "John", None, "Doe"], [2, "Jane", "group1", "Zee"], [3, "Lex", "group2", "Fee"]]

y = 2

for sublist in mylist:
    if sublist[y] == None:
        print(sublist[y]) # this should print nothing
    else:
        print(sublist[y]) #this should print something
</code></pre>

<p>If you want to check <em>any</em> field containing <code>None</code>, you get something like this:</p>

<pre><code>mylist = [ [1, "John", None, "Doe"], [2, "Jane", "group1", "Zee"], [3, "Lex", "group2", "Fee"]]

for sublist in mylist:
    for field in sublist:
        if field == None:
            print("None detected in: " + str(sublist))
</code></pre>

python python-3.x python-3.4