+ 1

Am confused šŸ¤” here, why it Outputs [0, 1, 8, 27, 64] anyone to help me.

cubes = [i**3 for i in range(5)] print(cubes)

3rd Mar 2022, 6:01 AM
David Mphande
David Mphande - avatar
9 Answers
+ 8
DAVID MPHANDE range(5) returns [0, 1, 2, 3, 4] So now get cubes of these values.
3rd Mar 2022, 6:24 AM
AĶ¢J
AĶ¢J - avatar
+ 6
Ooh šŸ˜® i get it now thanks šŸ˜Š AĶ¢J
3rd Mar 2022, 6:47 AM
David Mphande
David Mphande - avatar
+ 4
DAVID MPHANDE In python there are 3 range function which accept different parameters #if you dont provide end value #by default range will give value from 0 to exclude end value #exclude means end value will not be consider print(list(range(5))) #[0, 1, 2, 3, 4] ------------------- #range(start, end) #default step is 1 print(list(range(0, 5))) #[0, 1, 2, 3, 4] -------------------- #range(start, end, step) print(list(range(0, 50, 5))) #[0, 5, 10, 15, 20, 25, 30, 40, 45]
3rd Mar 2022, 8:23 AM
AĶ¢J
AĶ¢J - avatar
+ 3
Your syntax is like range(start, stop, step) So it takes step of 5 numbers that's why 0,5,10,... So on. Also, In python the loop stop at stop but it does not include the number that's why loop doesn't include 50 at last
3rd Mar 2022, 8:43 AM
Muskan Dhawan
+ 3
I get it...... range(5) returns [0, 1, 2, 3, 4] 0 ** 3, 1 ** 3, 2 ** 3, 3 ** 3, 4 ** 3 0 1 8 27 64 print([0 ** 3, 1 ** 3, 2 ** 3, 3 ** 3, 4 ** 3]) Output: [0, 1, 8, 27, 64]
21st Apr 2022, 8:37 AM
David Mphande
David Mphande - avatar
+ 2
What do you think caused these numbers? More specifically: what values of i can cause these outputs?
3rd Mar 2022, 6:05 AM
HungryTradie
HungryTradie - avatar
+ 2
By default index starts from 0, given range 5 it will follow the loop of 0 to 4 ie. 0,1,2,3,4. And your logic i**3 asking it to produce cubes so. Loop will work as 0**3= 0 1**3= 1 2**3= 8 3**3= 27 4**3= 64
3rd Mar 2022, 8:26 AM
Muskan Dhawan
+ 2
Muskan Dhawan thank you
3rd Mar 2022, 8:42 AM
David Mphande
David Mphande - avatar
+ 1
AĶ¢J here why it skips 5 numbers. print(list(range(0, 50, 5))) #[0, 5, 10, 15, 20, 25, 30, 40, 45]
3rd Mar 2022, 8:31 AM
David Mphande
David Mphande - avatar