views:

103

answers:

4
M = [[1,2,3],
     [4,5,6],
     [7,8,9]]

col2 = [row[1] + 1 for row in M if row[1] % 2 == 0]
print (col2)

Output: [3, 9]

I'm expecting it to filter out the odd numbers, but it does the opposite.

+6  A: 

The code is doing exactly what you would expect - if the second item is even, increase it by one and put it into the list.

So for the first row, it sees that 2 % 2 == 0 is True, and sets col2[0] = 2 + 1 = 3. For the second row, 5 % 2 == 0 is False. For the third row, 8%2 == 0 is True, and col2[1] = 8 + 1 = 9.

Daniel G
Oh, so it reads the IF statement first? I thought statements were processed left-t-right?
Nimbuz
Yes - list comprehensions allow multiple conditions after the for loop, and the expression on the left is evaluated after considering all of those conditions. (technical explanation: http://docs.python.org/reference/expressions.html#list-displays)
Daniel G
A: 

You are testing row[1]%2, but printing row[1]+1
so when row[1]==2, it is even, but you are appending 3 to the result
when row[1]==5, it is odd, so you filter it out
and when row[1]==8, it is even, but you are appending 9 to the result

gnibbler
+2  A: 

I believe you need to switch the comparison to == 1 from == 0.

The modulus of any number divided by 2 is 0 or 1, 1 when it is odd.

warren
Hmm..not really. I tried this: for n in range(10): n = n % 2 and it printed ODD as '0'
Nimbuz
A: 
M = [[1,2,3],
    [4,5,6],
    [7,8,9]]
col2 = []

for row in M:
    if row[1]%2 == 1:
        col2.append(row[1])
print col2
inspectorG4dget