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
3 Answers
+ 3
If, "if" returns true then the value of i will get appended to the list or else it won't
+ 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].
+ 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