3
$\begingroup$

Is there a special keyword to get the current index in Scan ?
For example, let say I have the following code :

Scan[Print[#] &, {2, 5, 7}]

It print the content of the list :

2
5
7

How to modify the code to print the current index also ?

1,2
2,5
3,7
$\endgroup$
1
  • $\begingroup$ This question has essentially the same answer as this one. Should it be tagged as a duplicate? $\endgroup$
    – m_goldberg
    Aug 20 '14 at 9:40
5
$\begingroup$
MapIndexed[Print[Row[{First@#2, #1}, ","]] &, {2, 5, 7}];
1,2
2,5
3,7

Or simpler:

MapIndexed[Print[First@#2, ",", #1] &, {2, 5, 7}]
1,2
2,5
3,7
$\endgroup$
7
$\begingroup$

A scan operation doesn't really have an index, but you can get the effect you want by introducing a counter.

Module[{i = 0}, Scan[(i++; Print[i, ", ", #]) &, {2, 5, 7}]]

output

You might also consider using Do, which does have an index.

With[{data = {2, 5, 7}}, 
  Do[Print[i, ", ", data[[i]]], {i, Length @ data}]]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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