# Strange behaviour

I am new to Sage, so please help me understand the following: How come

map(lambda x: mod(x,2),[4,3,2,1,1])

returns the perfectly sane answer [0,1,0,1,1]

but trying to compute the sum

sum(map(lambda x: mod(x,2),[4,3,2,1,1]))

gives the value 1, and not 3. Somehow, it seems that sage thinks that I wish to apply the inner lambda again on the result of the sum.

edit retag close merge delete

Sort by ยป oldest newest most voted

You can try

map(lambda x: x%2,[4,3,2,1,1])

then

sum(map(lambda x: x%2,[4,3,2,1,1]))

will return the desired output.

What happens when you use mod(x,2) is that sage returns an element of $\mathbb{Z}_2$, however the % operator returns an Integer.

more

To put it another way, that means that the sum of mod(x,2) being either zero or one is a feature, not a bug!

( 2013-07-05 14:14:52 -0500 )edit
1

I would prefer comprehension sum(x%2 for x in [4,3,2,1,1]) rather than map.

( 2013-07-06 04:16:55 -0500 )edit

Aha! Cool! That makes sense.

( 2013-07-06 05:08:31 -0500 )edit