Advanced Topics in Python : List Comprehension Syntax


#1

Help Please I'm Not Sure Where I Have Gone Wrong

doubles_by_3 = [x*2 for x in range(1,6) if (x*2) % 3 == 0]

Complete the following line. Use the line above for help.

even_squares = [y for y in range(1,50) if y **y and 2 % == 0]
print even_squares

Explanations Are Greatly Appreciated

  • SwitchGM

#2

We need three parts to create this expression:

  1. What we want to calculate.
  2. In what range we want to operate.
  3. What condition must be met.

Answers to all these questions can be found in instruction:

Your even_squares list should include the squares [1] of the even numbers [3] between 1 to 11 [2]. Your list should start [4, 16, 36...] and go from there.

Answers:

  1. We want to calculate squares -> y * y or y**2.
  2. We want to operate in range from 1 to 11 -> range(1, 11).
  3. We are interested in squares of even numbers only -> y % 2 == 0.

And now we only have to merge these answers in the right order:

even_squares = [y * y for y in range(1, 11) if y % 2 == 0]