Advanced Topics In Python 6/18 Is this necessary?


#1

I wrote my line of code and it worked, but when I looked at the Codecademy code I see that they use extra parantheses inside the if statement, but is it really necessary?

My code:

cubes_by_four = [x ** 3 for x in range(1, 11) if (x ** 3) % 4 == 0]

Codecademy code:

cubes_by_four = [x ** 3 for x in range(1, 11) if ((x ** 3) % 4) == 0]


#2

The parens are not needed. When in doubt you can use them, but one should be aware of order of operations and precedence. In this case, exponentation precedes modulo division so the parens are redundant.


#3

Thats what I thought…wonder why they put them in their solution in this case when they are not needed…Codecademy should do somtheing about the unecessary things like that in their code


#4

That would be a question for the author. Can’t say. (Habit, could be one possible reason.)

http://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.html

Note in the above chart where ** is in relation to %. The higher in the chart, the higher the precedence.


#5

Yes the ** comes first, so doing (x ** 3) % 4 is understandable, but doing ((x ** 3) % 4) is pointless

Just like 3 + 4 * 5 could be written 3 + (4 * 5)…if we wrote (3 + (4 * 5)) it would be pointless


#6

Try this…

c = [x ** 3 for x in range(1, 11) if x ** 3 % 4 == 0]

Not grouping required. Grouping is how we enforce our own order of operations. There is no need to enforce it here.

Here we would need grouping…

c = [x ** 3 for x in range(1, 11) if not (x ** 3 % 4)]

Again, check where * is in the list compared to +. Multiplication over addition is the simple rule. Division over subtraction, is implied since division is a form of multiplication, and subtraction is a form of addition.

3 + 4 * 5  =>  23

We would only group if we wanted to do the addition first.

(3 + 4) * 5  =>  35

#7

Yes of course, you are right, as you said even the parantheses in my code are unecessary, I just put them there because of an earlier example we were given by Codecademy without thinking, but of course they are pointless in my case cubes_by_four = [x ** 3 for x in range(1, 11) if (x ** 3) % 4 == 0]


#8

So long as you know the reason to use them, what you do is up to you. In the above example, no brackets are needed.

if x ** 3 % 4 == 0

is just fine. Precedence rules over order.


#9

Exactly, I just removed them from my notes :wink:


#10

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.