1

I wrote a line that should sum up all numbers of a string except 0. On a zero it should add 5.

Whats wrong with

s="123450"
o=sum([int(x) for x in s if int(x) != 0 else 5])

it gives syntax error, but

s="123450"
o=sum([int(x) for x in s if int(x) != 0])

works fine.

Sampleman
  • 45
  • 3

3 Answers3

8

if at the end of a list comprehension is used as a filter. It can only cause values to be dropped, not replace them with other things. To map values, you have to move the if/else earlier in the comprehension:

o=sum([int(x) if int(x) != 0 else 5 for x in s])
0x5453
  • 12,753
  • 1
  • 32
  • 61
1

The correct syntax for the first case if -

s="123450"
o=sum([int(x) if int(x) != 0 else 5 for x in s ])
print(o)

OUTPUT :

20

There are many good answers already available on StackOverflow over if-else in list comprehension. Check these -

Abhishek Bhagate
  • 5,583
  • 3
  • 15
  • 32
1

More of an aside really (as the general issue of how you are using if inside list comprehensions is well covered in other answers), in this particular case you could do the following:

o = sum(int(x) or 5 for x in s)

This works because or will use the first value if it is "true" (which in the case of integers means non-zero) or the second value if the first is "false" (here, 0).

The other difference here is that I've used a generator expression instead of a list comprehension -- there is no need to build a list just in order to sum the values.

alani
  • 12,573
  • 2
  • 13
  • 23