Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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)
share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

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)
share|improve this answer
    
Instead of using a separate counter to access the items in the list, use enumerate. –  Paul Jun 27 '13 at 13:38
    
Good thought, Paul. Added it to the answer. Thanks! –  csd Jun 27 '13 at 14:00
    
It worked. Thanks! –  Ibe Jun 27 '13 at 14:00
add comment

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.