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.
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.
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.
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
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.
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