Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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
share|improve this question
    
This question has essentially the same answer as this one. Should it be tagged as a duplicate? –  m_goldberg Aug 20 at 9:40

2 Answers 2

up vote 5 down vote accepted
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
share|improve this answer

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}]]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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