0

I am using an update cursor to update the attributes of a shapefile using values from a list. It seems very easy, but I couldn't make it run correctly. When I run the following code, it updates all rows based on the final value in the list. Please suggest how to fix it.

cur1 = arcpy.UpdateCursor(fc)
for v in cur1:
    for s in list:
        val = s
        v.Val = val
        cur1.updateRow(v)

1 Answer 1

3

This looks like a simple logic error. I'm assuming that you want the first feature in the cursor to be updated with the first item in the list, then the second feature with the second item, etc. As written, you're updating the same row over and over again with each element of the list. (Then repeating the process for each row.)

Maybe your loop should look something like this instead:

listIndex = 0
cur1 = arcpy.UpdateCursor(fc)
for c in cur1:
    if listIndex >= len(list):
        arcpy.AddMessage("More rows than items in the list.  Quitting early.")
        break
    val = list[listIndex]
    v.Val = val
    cur1.updateRow(v)
    listIndex = listIndex + 1

EDIT: Corrected logic error (needed to check array length before accessing it, not after). Also fixed missing : on if statement.

EDIT: Following the suggestion in Paul's comment is more "Pythonic" and reduces the lines of code:

cur1 = arcpy.UpdateCursor(fc)
for tuple in enumerate(cur1):
    index = tuple[0]
    row = tuple[1]
    if index >= len(list):
        arcpy.AddMessage("More rows than items in the list.  Quitting early.")
        break
    row.Val = list[index]
    cur1.updateRow(row)
2
  • Instead of using a separate counter to access the items in the list, use enumerate.
    – Paul
    Jun 27, 2013 at 13:38
  • Good thought, Paul. Added it to the answer. Thanks!
    – csd
    Jun 27, 2013 at 14:00

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.