I was doing an exercise that consisted of using a list comprehension (LC) to add the odd numbers between 0 and 10. To do this, it first occurred to me to use the for loop, analyze its structure and then pass it to an LC. The problem is that when using this for loop:
for i in range(10):
if i%2 != 0:
print(sum([i]))
I didn't get the desired result, just a list of numbers. Instead, when using LC
sum([i for i in range(10) if i%2 !=0])
the sum was correct. Could someone guide me on the error? I'm pretty new to Python and I can't find any reference to help me solve this issue. Thanks in advance :)
The explanation is very simple.
In your first code you are making a loop that goes from
0 - 10
and if the number is odd, then you print thesum
number itself (so it prints it without further ado)In the second code, you're making a list of numbers and then you add them to the list, so you get the final result.
In the first example you should save the odd elements in a list and at the end of the loop, do a
sum
to get the expected result.online example