AnsweredAssumed Answered

Cursor cannot update field because of IndexError

Question asked by jpilbeam Champion on Oct 15, 2020
Latest reply on Oct 15, 2020 by jpilbeam

I'm using arcpy.da.UpdateCursor and split() to update the unit name field of my table with an element from a list.

 

This executes successfully:

import arcpy

#fields from the feature class table
field = ['Unit', 'UnitName']

#use a cursor to parse the table of the feature class
with arcpy.da.UpdateCursor(fc, field) as cursor:
    for row in cursor:
        unit = row[0] #get Unit in field list
        s = str(unit).split() #split strings in Unit field
        print(s) #print list

 

Here are a few examples of what prints out:

['200']
['STE', '112']
['STE', 'L']
['UNIT', 'A']
['STE', 'B']
['STE', 'A']
['None']
['None']

 

But, when I put an index number on the print statement I get the IndexError: list index out of range. Funny thing is I don't get the error right away. A bunch of elements are printed before the error occurs. I think it is because of the None elements.

import arcpy

#fields from the feature class table
field = ['Unit', 'UnitName']

#use a cursor to parse the table of the feature class
with arcpy.da.UpdateCursor(fc, field) as cursor:
    for row in cursor:
        unit = row[1] #get Unit in field list
        s = str(unit).split() #split strings in Unit field
        print(s[1]) #print element in second position
        row[1] = s[1] #create variable for the element
        cursor.updateRow(row) #use cursor to update "UnitName" field with element in second position

 

Prints:

200
112
L
A
B
A
Traceback (most recent call last):
  File "\GISstaff\Jared\Python Scripts\ArcGISPro\USPS_ADDRE_copy.py", line 40, in <module>
    unitname()
  File "\GISstaff\Jared\Python Scripts\ArcGISPro\USPS_ADDRE_copy.py", line 34, in unitname
    print(s[1])
IndexError: list index out of range

Outcomes