2

I have written a python script that iterates through the field of a table using the SearchCursor and produces two table field and the i want to add a number to the individual values in a field produced. The codes seems to work on only one number.Please help what I am missing in my codes: The code is :

import arcpy
fc = arcpy.GetParameterAsText(2)

rows = arcpy.da.SearchCursor(fc,['S10','S100'])
for i in range(2,7,2):
        arcpy.AddMessage("When i is {0}".format(i))
        for row in rows:
                if row[0]:
                        new_row = row[0]+i
                        arcpy.AddMessage(new_row)

The out put i get:

 When i is 2
   2.275
   2.342
   2.257
   2.667
 When i is 4
 when i is 6

QN: Why is not iterating when i is 4 and 6?

4

The da.SearchCursor is an iterator meaning that you can iterate through it only once.

After you've gone through the loop of for row in rows, the iterator is exhausted and you won't be able to get any rows. To solve this, just call the rows.reset() to return to the first row and iterate again.

import arcpy
fc = arcpy.GetParameterAsText(2)

rows = arcpy.da.SearchCursor(fc,['S10','S100'])
for i in range(2,7,2):
    arcpy.AddMessage("When i is {0}".format(i))
    rows.reset()
    for row in rows:
        if row[0]:
            new_row = row[0]+i
            arcpy.AddMessage(new_row)

If you would need to work with the features a lot, it may be worth reading all the features from the cursor once and save them in a list which you could iterate. Then you won't need to reset the cursor each time you would like to get back to its first row. However, be careful if you are working with large datasets (many millions rows) as creating a list takes time and RAM is necessary to store it during the script execution.

This can be done with a simple list comprehension:

rows = [f for f in arcpy.da.SearchCursor(fc,['S10','S100'])]
  • @stasha, awesome. Just added a quick comment on how you could built a list so you won't need to reset it all the time. – Alex Tereshenkov Nov 9 '17 at 15:16

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.