0
$\begingroup$

I'd like to produce a list of $n-$tuples made from the elements of Range[n] coupled with a constant value $m$.

Here's an example, given $n=3$:

Range[3] = {1,2,3}

What I want to obtain is:

{{1,m},{2,m},{3,m}}

I've tried using Tuple, but I couldn't get it to make what I want.

$\endgroup$
1
  • $\begingroup$ Related: (7996) $\endgroup$
    – Mr.Wizard
    Nov 15, 2019 at 9:01

3 Answers 3

3
$\begingroup$

You can in fact use Tuples[]:

Tuples[{{1, 2, 3}, {"m"}}]
   {{1, "m"}, {2, "m"}, {3, "m"}}
$\endgroup$
4
  • $\begingroup$ Is the "m" the same as m? $\endgroup$
    – Rodrigo
    Nov 15, 2019 at 6:59
  • $\begingroup$ You can replace "m" with anything else; try it out yourself. $\endgroup$ Nov 15, 2019 at 7:00
  • $\begingroup$ I've tried. Thanks a lot! (Sorry if the question was a bit basic.) $\endgroup$
    – Rodrigo
    Nov 15, 2019 at 7:02
  • 1
    $\begingroup$ @Rodrigo You can make explicit use of Symbol which I sometimes like to make the character of m more explicit, e.g. Symbol["m"]. $\endgroup$
    – gwr
    Nov 15, 2019 at 9:27
3
$\begingroup$

Benchmark in Mathematica 10.1 of the posted methods, plus one using ArrayFlatten:

tuples[n_] := Tuples[{Range@n, {m}}];
thread[n_] := Thread[{Range@n, m}];
array[n_] := Array[{#, m} &, n];
transpose[n_] := Transpose@{Range@n, ConstantArray[m, n]};
arrayflatten[n_] := ArrayFlatten[{{Range@n ~Partition~ 1, m}}];

m = 17;

Needs["GeneralUtilities`"]
BenchmarkPlot[{tuples, thread, array, transpose, arrayflatten}, Identity]

enter image description here

$\endgroup$
1
$\begingroup$

Something like this?

Block[{n = 3}, Array[{#, m} &, n]]
Transpose@{Range[3], ConstantArray[m, 3]} == %
Thread@{Range[3], m} == %%

{{1, m}, {2, m}, {3, m}}

True

True

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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