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,
7 Réponses
+ 4
1**3 or math.pow(1,3) equals to 1³ which is 1*1*1
+ 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
+ 2
Thanks all four your answers. I understand better :)
+ 1
range(5) is basically equal to a list of 1 through 4. Do the math on each of those numbers
+ 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 ^^'
+ 1
Visualize your code execution (step by step)
(Python, Java, C, C++, JavaScript, Ruby)
https://pythontutor.com
+ 1
for i in range(5)
mean, that
start -> from zero(0), stop -> (5-1)