List Comprehension


#1

https://www.codecademy.com/courses/python-beginner-en-KAgt5/1/3?curriculum_id=4f89dab3d788890003000096

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

print cubes_by_four

That is my code. I keep getting an error message:

Oops, try again. Looks like cubes_by_four is the wrong length. It should have 5 values.

I'm not sure what is wrong. I see no typos. Would you be so kind as to tell me where is the issue?


#2

It should be range(1, 11).


#3

Thanks! The exercise said: The comprehension should consist of the cubes of the numbers 1 through 10 only if the cube is evenly divisible by four. So I kind of stuck with that. Am I to understand that you always need to add +1 to the range?


#4

range([start], stop[, step])

  • start: Starting number of the sequence.
  • stop: Generate numbers up to, but not including this number.
  • step: Difference between each number in the sequence.

>>> for i in range(5):
...     print(i)
... 
0
1
2
3
4

>>> for i in range(3, 6):
...     print(i)
... 
3
4
5

>>> for i in range(4, 10, 2):
...     print(i)
... 
4
6
8

#5

Okay, thanks! I understand it now :slight_smile:


#6

Glad I could help :slight_smile:


#7

Try this.

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


#8

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