List Comprehensions | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

List Comprehensions

Could someone help me understand this code here below? A list comprehension can also contain an if statement to enforce a condition on values in the list. Example: evens=[i**2 for i in range(10) if i**2 % 2 == 0] print(evens) Result: >>> [0, 4, 16, 36, 64] >>> What does this code mean, could someone break it down for me. Thanks

26th Jan 2020, 1:16 AM
Titus Gitari
Titus Gitari - avatar
3 Answers
+ 3
If, "if" returns true then the value of i will get appended to the list or else it won't
26th Jan 2020, 2:55 PM
Terminal_Phantom
Terminal_Phantom - avatar
+ 1
It's basically generating a list of the squares up to ten that have a even square root. Let's take a look: Iteration 1: 0 is appended to evens, because 0 ** 2(which returns 0) is even(or can be divided by 2). Iteration 2: 1 is not even, so we don't get the square of it. Iteration 3: 4 is appended to evens, as 2 is even and it's square is 4. Iteration 4: 3 is not even, so we don't get the squares of it. Iteration 5: 16 is appended to evens, as 4 is even and it's square is 16. Iteration 6: 5 is not even, so we don't get the square if it. Iteration 7: 36 is appended to evens, as 6 is even and it's square is 36. Iteration 8: 7 is not even, so we don't get the square of it. Iteration 9: 64 is appended to evens, as 8 is even and it's square is 64. Iteration 10: 10 is not even, so we don't get the square of it. This means evens is [0, 4, 16, 36, 64].
26th Jan 2020, 2:06 AM
Jianmin Chen
Jianmin Chen - avatar
+ 1
Please, if you like, read this tutorial of comprehension, and tell me if it clarifies things for you. https://code.sololearn.com/ck6HicJ6Z8jG/?ref=app
26th Jan 2020, 9:42 AM
HonFu
HonFu - avatar