# Empty list in sum create an error

I would to define a constraint in jump using this compact notation like:

``````sum( sum(  Flow[p,j] for j in A[p] if j == "TT" ) for p in  pars) )
``````

the problem is that for a given p, there may be no “TT” in A[p] list and in this cas it generate an empty list and I got this error:

`````` ArgumentError: reducing over an empty collection is not allowed
``````

There’s a solution with two for loop:

``````ex = AffExpr()
for p in  pars
for  j in A[p]
if j == "TT"
ex += Flow[p,j]

....
``````

but I’m wondering if there a way keep compact fomuraltion?

Thanks

• Pascal

Instead of `sum( Flow[p,j] for j in A[p] if j == "TT")`, do `reduce(+, Flow[p,j] for j in A[p] if j == "TT", init=zero(eltype(Flow)))`. By providing the `init` argument, you give it a way to handle empty collections. I used `zero(eltype(Flow))` to ensure that it always returns something of the same type, since I don’t know what your `Flow` array contains.

1 Like

eltype(Flow) return Pair{Any,Any} and then zero( ) function call failed with
MethodError: no method matching zero(::Type{Pair{Any,Any}})

You will have to poste a full MWE for us to help you more, unfortunately.

Also, note that you quote code with backticks

```````like this`
``````
1 Like

Ok I find it.
reduce(+, [Flow[p,j] for j in A[p] if j == “TT”], init=zero(1) )
works fine.

1 Like

Ok thanks, I new here and in Julia too.

From your code above, it seems like you want `init=AffExpr()`.

3 Likes