# Extracting the integers from a list

I have a list where the elements are Reals and Integers. How can I extract the Integer? For example, if I have {1, 2, 3.4, 9.9}, how can I get {1, 2}?

Try this command

Cases[list, _Integer]

• Thanks.. it runs. But when i erase the {1} at the end of the command, it also runs. What is the meaning of {1}? Apr 13, 2013 at 10:53
• To just check on the first level of the list. Actually by default it takes {1} so I better remove it too! Apr 13, 2013 at 10:58

Well since we're having fun, I'll like to join the party:

lst = {3, 5.6, 8.19, 2, 5.6, 4, 3, 8.5, 4.137, 7., 1.165}

DeleteCases[lst, _Real]


OR

lst /. x_Real -> Sequence[]


OR

Select[lst, Head[#] == Integer &]


All give:

{3, 2, 4, 3}

• @Mr.Wizard, Thanks, you got my vote too :) Apr 14, 2013 at 0:16
• I added a couple more to my answer. I hope you enjoy them. Apr 14, 2013 at 0:17
• Why not Select[lst, IntegerQ]? Apr 14, 2013 at 1:41
• @J.M., that too. Isn't Head[#]==Integer& what MMA is doing under the hood when you use IntegerQ? Apr 14, 2013 at 2:42
• I suppose, but I would think IntegerQ is idiomatic, while the actual head test is more literal. :) Apr 14, 2013 at 2:44

Just for fun, here's a terse method using Pick:

lst = {3, 5.6, 8.19, 2, 5.6, 4, 3, 8.5, 4.137, 7., 1.165}

Pick[#,#-#,0]& @ lst

{3, 2, 4, 3}


More fun:

Replace[lst, _Real|x_ :> x, 1]

{3, 2, 4, 3}


Only for positive values:

Log@lst ~Level~ {2}

{3, 2, 4, 3}

• Oh wow, that last one using Log is clever, wish I could Upvote again. Apr 14, 2013 at 0:21

Here's another one, for fun:

lst = {3, 5.6, 8.19, 2, 5.6, 4, 3, 8.5, 4.137, 7., 1.165};
Pick[lst, Mod[lst, 1], 0]
(* {3, 2, 4, 3} *)

• ...or SawtoothWave[lst]. Apr 14, 2013 at 14:10
• .. or Gamma[lst] - (lst - 1)! :D
– rm -rf
Apr 14, 2013 at 14:12

if order does not matter:

Attributes[f] = {Orderless};
f[x__Integer, __] := {x}
f @@ {3, 5.6, 8.19, 2, 5.6, 4, 3, 8.5, 4.137, 7., 1.165}

(* {2, 3, 3, 4} *)

Select[lst, Round[#] == #&];
Select[lst, # == Round[#]&];