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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.