How to remove empty array of a list of array

I have a vector that might look like these forms :

list_temp = Any[(Any[(“Bus1”, “Bus2"”), (“Bus2”, “Bus1”)],), (Any,)]
list_temp = Any[(Any,), (Any[(“Madagascar1”, “Madagascar2”)],)]

I would like to remove any empty arrays inside my vector.
I have tried:

new_list=[s for s in list_temp if !isempty(s)]

but it does not really remove empty values.
Anyone knows how can I deal with it?

It looks like the things you want to remove are tuples of length one containing empty arrays. You can’t test the tuple for emptiness directly since it does in fact contain an element.

julia> x = (Any[],)

julia> isempty(x)

julia> length(x)

Instead you can use dot broadcasting to apply the emptiness test on each element of the tuple

julia> isempty.(x)

and reduce it to a boolean with all

julia> all(isempty.(x))

This finally leads to

[s for s in list_temp if !all(isempty.(s))]

which might do what you want.

1 Like

If you want to remove any occurence of (Any,) the 1-tuple holding the Julia type Any, that is different from wanting to remove any empty tuples (the empty tuple is ().
In any event:

julia> alist = [(1,2), (), ("a", "b"), ()]
4-element Array{Tuple,1}:
 (1, 2)
 ("a", "b")

julia> blist = filter(!isempty, alist)
2-element Array{Tuple,1}:
 (1, 2)
 ("a", "b")

You can filter in place, too

julia> alist = [(1,2), (), ("a", "b"), ()];
julia> filter!(!isempty, alist);
julia> alist
2-element Array{Tuple,1}:
 (1, 2)
 ("a", "b")


julia> alist = [(1,2), (Any,), ("a", "b"), (Any,)]
4-element Array{Tuple{Any,Vararg{Any,N} where N},1}:
 (1, 2)
 ("a", "b")

julia> blist = filter(x->x!=(Any,), alist)
2-element Array{Tuple{Any,Vararg{Any,N} where N},1}:
 (1, 2)
 ("a", "b")