# Iteration over collections with unassigned entries

**URL:** <https://discourse.julialang.org/t/iteration-over-collections-with-unassigned-entries/9344>\
**Category:** General Usage\
**Created:** [February 26, 2018, 4:19pm UTC](https://discourse.julialang.org/t/iteration-over-collections-with-unassigned-entries/9344 "2018-02-26T16:19:34Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![pablosanjose](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/pablosanjose/32/7006_2.png) [@pablosanjose](https://discourse.julialang.org/u/pablosanjose)\
**Post date:** [February 26, 2018, 4:19pm UTC](https://discourse.julialang.org/t/iteration-over-collections-with-unassigned-entries/9344/1 "2018-02-26T16:19:34Z")

</div>

How does one handle `#undef` entries in a comprehension over a collection?

Say I have

```julia
julia> struct Foo
           v::Vector{Int}
       end

julia> bar = Vector{Foo}(uninitialized, 3); bar[1] = Foo([1]); bar[3] = Foo([3,4]);

julia> bar
3-element Array{Foo,1}:
    Foo([1])   
 #undef        
    Foo([3, 4])

```

Now I want to build an `Bool` array `b` that says whether each element of `bar` corresponds to an empty or unassigned vector. I try to write

```julia
julia> b = [isempty(f.v) for f in bar]
ERROR: UndefRefError: access to undefined reference
...

```

This also fails

```julia
julia> b = [!isassigned(bar, i) || isempty(f.v) for (i,f) in enumerate(bar)]
ERROR: UndefRefError: access to undefined reference

```

Same problem in other contexts such as `all(isempty(f.v) for f in bar)` for example.

Is there an elegant way to handle `#undef`s in this kind of iterations without writing out an explicit loop?

[EDIT: This works, but I still wonder if there is a cleaner way

```julia
b = [!isassigned(bar, i) || isempty(bar[i].v) for i in eachindex(bar)]

```

Maybe this is good enough… Sorry for the noise]

---

<div class="post-metadata">

**Author:** ![quinnj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/quinnj/32/11_2.png) [@quinnj](https://discourse.julialang.org/u/quinnj)\
**Post date:** [February 26, 2018, 4:37pm UTC](https://discourse.julialang.org/t/iteration-over-collections-with-unassigned-entries/9344/2 "2018-02-26T16:37:55Z")

</div>

Yeah, the issue here is `[... for f in bar]`, which implicitly does `bar[i]`, which will error on `#undef`. Your `eachindex(bar)` solution is probably the best.
