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)
Chad Cooper
12.8k4 gold badges48 silver badges87 bronze badges
asked Jun 27, 2013 at 13:21

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)
Chad Cooper
12.8k4 gold badges48 silver badges87 bronze badges
answered Jun 27, 2013 at 13:35
2
  • Instead of using a separate counter to access the items in the list, use enumerate. Commented Jun 27, 2013 at 13:38
  • Good thought, Paul. Added it to the answer. Thanks! Commented Jun 27, 2013 at 14:00

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.