8
$\begingroup$

My goal is to add an index to all elements of a list in the form {"a", "b", "c", ... }, so it becomes {"N1 a", "N2 b", "N3 c" ... }, where the elements of the list are strings.

My current method is (sequence is a pre-defined list):

sequence = 
  Table[
    "N" <> ToString[i] <> " " <> ToString[sequence[[i]]], 
    {i, 1, Length[sequence]}];

I wonder if there's a more clever approach to this, since using Table seems like an overkill.

I can append a string to every element using:

sequence = 
  Replace[sequence, x_?StringQ :> "Test " <> ToString[x], All];

But here I don't know how to include the position/index of the elements, since they're not unique and I cannot use Position to determine their index.

$\endgroup$

2 Answers 2

10
$\begingroup$

My goal is to add an index to all elements of a list in the form {"a", "b", "c", ... }, so it becomes {"N1 a", "N2 b", "N3 c" ... }

may be

seq={"a","b","c","d"};
MapIndexed["N"<>ToString[First@#2]<>" "<>#1&,seq]

gives

{"N1 a", "N2 b", "N3 c", "N4 d"}
$\endgroup$
3
  • $\begingroup$ That's brilliant, thank you! Also, could you please explain what #1 and #2 are? $\endgroup$
    – Androvich
    Commented Oct 14, 2017 at 0:55
  • 1
    $\begingroup$ @Androvich The #2 gives the index of the entry. And the #1 gives the entry itself. Please see help on MapIndexed. Very useful function to know about ! $\endgroup$
    – Nasser
    Commented Oct 14, 2017 at 0:58
  • $\begingroup$ Yeah, I looked into it and tried to play around with it, so it all makes sense now, thanks! $\endgroup$
    – Androvich
    Commented Oct 14, 2017 at 2:04
4
$\begingroup$
list = {"a", "b", "c", "d"};

Array["N" <> ToString@# <> " " <> list[[#]] &, Length@list]

{"N1 a", "N2 b", "N3 c", "N4 d"}

$\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.