10
$\begingroup$

I am new to Mathematica, still trying to familiarise myself with the language.

I have a list: {2,3,4}. How can I change it to {{1,1},{1,1,1},{1,1,1,1}}?

$\endgroup$
1
  • $\begingroup$ Also {2,3,4}//TakeList[ConstantArray[1, Total@#],#]& $\endgroup$
    – user1066
    Feb 4, 2021 at 22:19

2 Answers 2

11
$\begingroup$

You can do it like this for example:

ConstantArray[1,#]&/@{2,3,4}

{{1, 1}, {1, 1, 1}, {1, 1, 1, 1}}

$\endgroup$
2
  • $\begingroup$ That's perfect works! Thank you! $\endgroup$
    – Teng
    Aug 26, 2018 at 23:07
  • 2
    $\begingroup$ other options, just for fun: ArrayReshape[{1}, {#}, 1] & /@ {2, 3, 4}, PadRight[{1}, #, 1] & /@ {2, 3, 4}, Table[1, #] & /@ {2, 3, 4}, ... $\endgroup$ Aug 27, 2018 at 1:51
8
$\begingroup$

Here's another way:

list = {2, 3, 4};
Sign[Range[list]]
{{1, 1}, {1, 1, 1}, {1, 1, 1, 1}}

(with a little simplification from @AccidentalFourierTransform)

$\endgroup$
2
  • 3
    $\begingroup$ simpler: Sign[Range[list]], or 1 + 0 Range[{2, 3, 4}]. $\endgroup$ Aug 27, 2018 at 1:51
  • $\begingroup$ @bill s, Unitize seems to be cleaner ))). $\endgroup$
    – garej
    Aug 27, 2018 at 4:45

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.