Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Write this comprehension as a plain loop, and say what it gives for numbers = [1, 2, 3, 4, 5].
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. Read it in three parts: the filter if n != 3 at the end skips the 3. The choice n * n if n % 2 == 1 else -n gives a value for each item that remains. The loop is for n in numbers.
Check. 1 is odd: 1. 2 is even: -2. 3 is skipped. 4 is even: -4. 5 is odd: 25.
Answer: [1, -2, -4, 25].
Log in to join the discussion.
Loading…