I know this is an old thread but…I think you’re missing what santyago is asking because I had the same question when going through the exercise and landed here. I figured it out using different syntax without using x ** 2 twice. Some of the replies in this thread seem to be misleading.
The key is that whether you would use x ** 2 twice or not seems to depend on what you’re trying to achieve with the code. What the code is actually doing that you aren’t ‘seeing’ is important.
These three different versions of the code produce two different results:
even_squares = [x for x in range(1, 11) if (x ** 2) % 2 == 0]
even_squares_02 = [x ** 2 for x in range(1, 11) if x % 2 == 0]
even_squares_03 = [x ** 2 for x in range(1, 11) if (x ** 2) % 2 == 0]
print even_squares
print even_squares_02
print even_squares_03
Results:
[2, 4, 6, 8, 10]
[4, 16, 36, 64, 100]
[4, 16, 36, 64, 100]
Without too much coding jargon it seems like this is happening:
-
You are creating a variable that is a list.
-
Establishing what you will do to each item in the list BUT this is happening outside of any logical test. this is what is referred to as the ‘expression’.
-
Then you are CREATING the original list by initiating a FOR statement.
-
Establishing that each variable in the original list will come from a RANGE of numbers, 1-11. Producing the numbers: 2,4,6,8,10 as the original list.
-
Performing a logical test on the original list established by the RANGE
What you are printing with the different versions is either the original list, done by: using only one x ** 2 as part of the logical test and leaving only x in the “expression” part which leaves the list unmodified .
Or: printing/representing the results of the logical test by including that first x ** 2 prior to the FOR statement. By including it, you are essentially changing the list outside of any logical test to represent what the logical test is actually checking.
It’s interesting because it’s truly a question of whether you as the coder are interested in the numbers that produced the squares or the results of squaring the numbers. In other words: If 2 squared is 4: do I care about the 4 or the 2?