# 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}?

-
It's not too difficult to find this in Mathematica's documentation. Could you try that first before asking questions? –  Sjoerd C. de Vries Apr 13 '13 at 17:32

## 4 Answers

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}? –  MATIRMAK Apr 13 '13 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! –  Spawn1701D Apr 13 '13 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}

-
Thanks for playing! +1 –  Mr.Wizard Apr 14 '13 at 0:13
@Mr.Wizard, Thanks, you got my vote too :) –  RunnyKine Apr 14 '13 at 0:16
I added a couple more to my answer. I hope you enjoy them. –  Mr.Wizard Apr 14 '13 at 0:17
Why not Select[lst, IntegerQ]? –  Guess who it is. Apr 14 '13 at 1:41
@J.M., that too. Isn't Head[#]==Integer& what MMA is doing under the hood when you use IntegerQ? –  RunnyKine Apr 14 '13 at 2:42

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. –  RunnyKine Apr 14 '13 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]. –  Guess who it is. Apr 14 '13 at 14:10
.. or Gamma[lst] - (lst - 1)! :D –  The Toad Apr 14 '13 at 14:12