0
Can someone help me understand
So I’m learning list comprehension, I don’t seem t understand the first example of code it gives me. Cubes = [i**3 for i in range(5)] print(cubes) Output: [0, 1, 8, 27, 64] I just don’t understand where these numbers are coming from. I know if if only do i*3 it outputs multiples of 3. And if i do i+3 it starts the list at 3 and adds 1 for every new number. I just don’t get what i**3 is doing.
3 ответов
+ 2
Juat as what Hari Shankar said, “**” operater is for exponent, for example 2**3 means 2*2*2, and 3**2 means 3*3 and so on.
Cubes = [i ** 3 for i in range(5)]
Understand this from inside out. range(5) gives [0,1,2,3,4], so it comes to “for i in [0,1,2,3,4]”, which means i is 1, and then 2, and then 3, and so on.
Now we come to “i ** 3 for i in [0,1,2,3,4]”, this means for each i, we calculate i ** 3.
Which means:
i = 0 => i**3 = 0
i = 1 => i**3 = 1
i = 2 => i**3 = 8
i = 3 => i**3 = 27
i = 4 => i**3 = 64
Now we come to “Cubes = [i ** 3 for i in range(5)]”, which just means to list the previous results and assign the list to the variable “Cubes”.
Therefore, “print(Cubes)” prints the list, which is [0,1,8,27,64]
Alan
+ 1
'**' is Exponent operator. i**3 means i to the power 3. range(5) will give you list [0,1,2,3,4]. This statement is calculating cube of each element of this list and stores it in another list named 'Cubes'. Then print 'Cubes'.
+ 1
QWKKK thanks for explaining it like that, now it makes so much sense. You are a life savior!!