# Removing empty elements

I have data from people being asked for a result of the swab test - (1=pos, 2=neg, 3=not received, 4= inconclusive,9=ignored, empty cell= not applicable). I'm looking for a way to get rid of the not applicable cells. It does not say N/A or anything - they are just empty. So it looks something like this:

{,,,,,,,,,2,,,,,,1,,,,,2,,,,,,,,,,,,,,,,,,,,,,9,,,,,,1} How would I get rid of all empty ones and only keep the numbers?

• Could replace Null with Nothing, among other possibilities. Jul 11, 2021 at 15:42
• To add a minor variation to Domen's repertoire of answers: Cases[list, Except[Null]]
– Syed
Mar 10 at 4:51

The solution depends on how the empty value are represented. Furthermore, you can use any of the many Mathematica functions, such as DeleteCases, Select, Cases, Replace ...

(* Empty values represented with Null *)
arr = {, , , , , , , , , 2, , , , , , 1, , , , , 2, , , , , , , , , , , , , , , , , , , , , , 9, , , , , , 1};
DeleteCases[arr, Null]
Select[arr, Not[# === Null] &]
Cases[arr, _?NumericQ]
arr /. Null -> Nothing

(* {2, 1, 2, 9, 1} *)

(* Empty values represented with "" *)
arr = {"", "", "", "", "", "", "", "", "", 2, "", "", "", "", "", 1, "", "", "", "", 2, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", 9, "", "", "", "", "", 1};

DeleteCases[arr, ""]
Select[arr, # != "" &]
Cases[arr, _?NumericQ]
arr /. "" -> Nothing

(* {2, 1, 2, 9, 1} *)

• Depending on where the data is coming from and how it is displayed, it might also be filled with "" (i.e. empty strings). But only OP knows which one is true of course Jul 11, 2021 at 11:18
• Thank you. Unfortunately, not sure why that did not delete the empty ones. I instead of getting rid of empty ones I chose to go with Select[swabTest,NumberQ].. This then gave me only the ones with results in it. Jul 18, 2021 at 10:00
• @Pedro, I have expanded my answer with different possible ways of getting what you want. Jul 18, 2021 at 11:01
list = {, , , , , , , 2, , , , , , 1, , , , , 2, , , 9 , 1};


A few more possibilities:

1.

Using SequenceSplit (new in 11.3)

Flatten @ SequenceSplit[list, {Null}]


{2, 1, 2, 9, 1}

Or, more generally

Flatten @ SequenceSplit[list, {Except[_?NumericQ]}]


{2, 1, 2, 9, 1}

Performance disclaimer: SequenceSplit gets slow with long lists.

2.

Using DeleteCases

DeleteCases[Except[_?NumericQ]] @ list


{2, 1, 2, 9, 1}

3.

Using Extract

Extract[Position[list, _?NumericQ]] @ list


{2, 1, 2, 9, 1}

list = {, , , , , , , 2, , , , , , 1, , , , , 2, , , 9, 1};


Using Delete:

Delete[#, Position[#, Null]] &@list

(*{2, 1, 2, 9, 1}*)


Or using GroupBy:

GroupBy[list, NumericQ][True]

(*{2, 1, 2, 9, 1}*)