Turn a table into one list, keeping only some values.
What to build
One comprehension with two for parts and an if.
Requirements
- Read the table.
- Make one list of the squares of the even numbers, going row by row and left to right.
- Print the list.
Input
The first line has r. Each of the next r lines has some whole numbers.
Output
The list, printed with print.
Constraints
r is from 1 to 20, and each row has from 1 to 20 numbers.
Example
Input:
2
1 2 3
4 5 6
Output:
[4, 16, 36]
Why it works
The for parts read in the same order as nested loops would be written, so for row in grid comes before for x in row.
Examples
Example 1 · Input
2 1 2 3 4 5 6
Expected output
[4, 16, 36]
Example 2 · Input
1 1 3 5
Expected output
[]
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
A comprehension can have two for parts, in the same order as nested loops.
Hint 2
Put the if at the very end.
Solution
Show one correct solution (try it yourself first)
r = int(input()) grid = [[int(x) for x in input().split()] for _ in range(r)] print([x * x for row in grid for x in row if x % 2 == 0])