List Comprehension - Cube math inside | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

List Comprehension - Cube math inside

Hey everyone, This question may be way too simple or even stupid but I must ask. ### Code ### cubes = [i**3 for i in range(5)] print(cubes) ########## So the code is understandable but what I can't figure out is maths part. The output is: [0, 1, 8, 27, 64] Why this numbers? From which number Python start? I tried multiply few numbers to the cube but not the same result... Thank you for your understanding,

23rd Apr 2021, 6:27 PM
Da Silva Miguel
Da Silva Miguel - avatar
7 Answers
+ 4
1**3 or math.pow(1,3) equals to 1³ which is 1*1*1
23rd Apr 2021, 6:51 PM
Rohit
+ 2
range(5) returns the numbers starting from 0 up to but not including 5, where 5 is the stop value passed as an argument. So, 0 1 2 3 4 will be the respective values of i for each iteration. The resulting list is the cube of each of those numbers. You can give the range() constructor start, stop, and step arguments. By default start is 0 and step is 1. range(start, stop, step) https://docs.python.org/3/library/functions.html#func-range
23rd Apr 2021, 6:35 PM
ChaoticDawg
ChaoticDawg - avatar
+ 2
Thanks all four your answers. I understand better :)
23rd Apr 2021, 6:53 PM
Da Silva Miguel
Da Silva Miguel - avatar
+ 1
range(5) is basically equal to a list of 1 through 4. Do the math on each of those numbers
23rd Apr 2021, 6:30 PM
Slick
Slick - avatar
+ 1
Yeah that part I kinda understand. And I just remember Solo Learn Android app has a commentary section for each lesson. And there was an explanation: 0**3 = 0x0x0=0 1**3 = 1x1x1=1 2**3 = 2x2x2=8 and so on... I must say it was tricky ^^'
23rd Apr 2021, 6:32 PM
Da Silva Miguel
Da Silva Miguel - avatar
+ 1
Visualize your code execution (step by step) (Python, Java, C, C++, JavaScript, Ruby) https://pythontutor.com
23rd Apr 2021, 6:41 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 1
for i in range(5) mean, that start -> from zero(0), stop -> (5-1)
23rd Apr 2021, 6:44 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar