0

List comprehensions

Hello Ducks. I didn't understand the List comprehensions, can anyone explain me the following code, please. ------ CODE ------ cubes = [i**3 for i in range(5)] print(cubes) ------ OUTPUT ------ [0, 1, 8, 27, 64]

15th Aug 2020, 10:47 PM
Agt Reda
Agt Reda - avatar
10 Antworten
+ 1
same as: cubes = [] for i in range(5): cubes.append(i**3)
15th Aug 2020, 10:54 PM
Slick
Slick - avatar
+ 1
Slick if someone put i * 3. what is the value of i at the beginning before the miltiplication ?
16th Aug 2020, 12:53 AM
Agt Reda
Agt Reda - avatar
+ 1
and what about: for i in my_list: what it i equal to ?
16th Aug 2020, 1:51 AM
Agt Reda
Agt Reda - avatar
+ 1
what is my_list?
16th Aug 2020, 1:58 AM
Slick
Slick - avatar
0
I copied and pasted your code "Slick" but it doesn't print anything.
15th Aug 2020, 10:57 PM
Agt Reda
Agt Reda - avatar
0
yeah its cause i didnt tell it to. add the line: print(cubes)
15th Aug 2020, 10:58 PM
Slick
Slick - avatar
0
yes, I know. I didn't see the whole code.
15th Aug 2020, 11:04 PM
Agt Reda
Agt Reda - avatar
0
but yeah "i ** 3" what is the value of i ?
15th Aug 2020, 11:04 PM
Agt Reda
Agt Reda - avatar
0
it says for i in range(5). so i is 0,1,2,3, and 4
15th Aug 2020, 11:05 PM
Slick
Slick - avatar
0
It depends wich iteration youre on. for i in range(5): makes i equal to a number between 0-4. I would mess around and print loops so you can see how they work.
16th Aug 2020, 1:12 AM
Slick
Slick - avatar