Why does my cubes_by_four list not contain the right values?


#1

Question

Why does my cubes_by_four list not contain the right values?

Answer

Some of the most common issues are:

  1. Using the wrong range: recall that range() includes the first number and excludes the stopping number, so if we want to go from 1 to 25, we’d write range(1, 26)
  2. Incorrectly checking if the cube is divisible by four: to check if something is evenly divisible by a number, we write if x % number == 0
  3. Not cubing the number: to cube something, write x ** 3

FAQ: Learn Python - Advanced Topics in Python - Now You Try!
#3

I’m not sure if I’m doing this right, but my code adheres to what is written above and looks like this…

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

print cubes_by_four

However, it only prints the values [64, 512] rather than including the other three values that fit the code. What am I doing wrong?


#4

Solved it. I didn’t pay attention to the reminder saying that the cubed number must be divisible by 4, not the original number. My final code looks like this…

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

print cubes_by_four