Dexter
Dexter

Reputation: 197

How to write following code in list comprehension form?

Trying to convert following code in list comprehension form but I am getting syntax error for "+=" near else

def lucky_sum(a, b, c):
    ip = [a, b, c]
    sum = 0
    for i in ip:
        if i ==13:
            return sum
        else:
            sum+=i
    return sum

I tried this:

def lucky_sum(a, b, c):
    ip = [a, b, c]
    sum = 0
    res = [sum if i == 13 else sum += i for i in ip]
    return sum

Upvotes: 3

Views: 85

Answers (3)

user8408080
user8408080

Reputation: 2468

First of all: Don't do a list comprehension here. They exist, so you can create lists more easily.

Just to see if it is possible (with no external module) I tried and came up with this:

def lucky_sum2(*args):
    return sum(el if el != 13 else next(iter([])) for el in args)

It abuses the fact, that next(iter([])) raises a StopIteration (which will soon be deprecated, though).

Don't use this, please

Upvotes: 1

Jean-François Fabre
Jean-François Fabre

Reputation: 140178

List comprehension isn't adapted here, but that doesn't mean that we cannot use functionnal programming.

Use built-in sum and itertools.takewhile to end iteration when meeting 13. Creates a one-liner.

import itertools


def lucky_sum(a, b, c):
    return sum(itertools.takewhile(lambda x:x!=13,[a, b, c]))

print(lucky_sum(1,2,3))
print(lucky_sum(1,13,3))

prints 6 then 1

A variable number of arguments version:

def lucky_sum(*ip):
    return sum(itertools.takewhile(lambda x:x!=13,ip))

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71580

It's impossible to use list comprehension here, since you're assigning something (this case is +=, but still has = in it), so you have to stay with a loop, list comprehensions aren't the stuff that could be used for anything.

So stay with the loop.

Upvotes: 5

Related Questions