Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing the odd numbers in a list using list comprehension, for and if in one line

I am learning Python and I am trying out some exercises. I am trying to sum all the odd numbers from 0 to 9 using list comprehension, for and if in one line.

I tried the following code:

for idx in range(10): s = 0 if idx == 0 else s = [(i % 2) for i in range(10)][idx] * range(10)[idx] + s

but I get the following error:

SyntaxError: can't assign to conditional expression

I don't quite understand it.

Your advice will be appreciated.

like image 793
im7 Avatar asked Feb 03 '26 06:02

im7


2 Answers

very short oneliner:

sum(range(1,10,2))

but the real formula is for any n:

((n+1)//2)**2

With that one, you're able compute the sum for a very big n very quickly.

Back to the point, you cannot accumulate using a list comprehension, or it's very difficult/hacky to do, so sum is required here. So the most logical if requirements are "use a comprehension notation and an if" is:

sum(x for x in range(1,10) if x % 2)

Note that there's no need to put an extra [] in that case. It's a generator comprehension (avoids generating an extra list, sum doesn't need to have all the info at once.

like image 86
Jean-François Fabre Avatar answered Feb 05 '26 21:02

Jean-François Fabre


This is how you may do it

sum([x for x in range(1,10,2)])

Explaining why your code failed

Here is your code as given in the question

for idx in range(10):
    s = 0 if idx == 0 else ([(i % 2) for i in range(10)][idx] * range(10)[idx] + s)

in the else part you may give the value to be assigned to s ie, s= is not required.You may re-write it as

for idx in range(10):
    s = 0 if idx == 0 else ([(i % 2) for i in range(10)][idx] * range(10)[idx] + s)

The expression syntax for ternary operator in python is as follows

condition_is_true if condition else condition_is_false

Eg usage

value1 = 10
value2 = 20
a = 3
b = 4
value = value1 if a > b else value2
print value
#20
like image 30
Sarath Sadasivan Pillai Avatar answered Feb 05 '26 21:02

Sarath Sadasivan Pillai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!