I would like to determine which elements in a list are divisible by a specific number, lets say 3.

I generate a list with numbers:

numbers = Range[10];

I then use Divisible to create another list of equal length that has True and False entries related to whether or not the entry in numbers are divisible by 3:

In[1] := test = Divisible[numbers, 3]
Out[1] := {False, False, True, False, False, True, False, False, True, False}

The resulting list test thus acts as an index.

How would I go about adding all the items in numbers to a new list if their corresponding item in test is True?

  • $\begingroup$ Mike, regarding your edit: closing a question is not a judgement on the value of the question contents; it has more to do with site management and improved searching. For instance, personally I upvoted your question (it is well written and clear), and also voted to mark it as duplicate. Your specific question was answered below (Pick is tailor-made for your task); the closure just establishes a permanent link between this question and other(s), perhaps more general, that people interested in the topic of your question are likely to find useful. $\endgroup$ – MarcoB Mar 2 '17 at 2:29
  • $\begingroup$ Thank you for the explanation MarcoB, that makes perfect sense! $\endgroup$ – Mike Mar 2 '17 at 5:04

Pick does exactly what you need:

numbers = Range[10];
test = Divisible[numbers, 3];
Pick[numbers, test]

{3, 6, 9}

  • $\begingroup$ Thank you. Is there a way to use a conditional inside Divisible to simultaneously check for divisibility? Say, if I want to check if a number is either divisible by 3 OR 5? $\endgroup$ – Mike Mar 2 '17 at 1:14
  • $\begingroup$ @Mike, i am not sure if you can do it with Divisible but you can use Divisors and MemberQ like MemberQ[Divisors[#], 3 | 5] & /@ Range[10] $\endgroup$ – kglr Mar 2 '17 at 1:21

you can use Select without having to create the list of Boolean values True, Falseexplicitly

Select[Range[10], Divisible[#, 3] &]
(* {3,6,9} *)

Alternatively one can use Extract

Extract[#, Position[Mod[#, 3], 0]] &@Range[10]

Cases can also be used

Cases[Range[10], _?(Mod[#, 3] == 0 &)]

using Patterns

Range[10] /. x_ /; ! Mod[x, 3] == 0 :> Sequence[]

using Part

Range[10][[3 ;; ;; 3]]

there are many ways you can use to get the answer in Mathematica.


Not the answer you're looking for? Browse other questions tagged or ask your own question.