Select to view content in your preferred language

Cursor cannot update field because of IndexError

570
2
10-15-2020 07:27 AM
JaredPilbeam2
MVP Regular Contributor

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‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
0 Kudos
2 Replies
JoshuaBixby
MVP Esteemed Contributor

I think it is because of the None elements.

It is exactly because of the None elements.  One way to avoid this error is to put an additional logical check after you retrieve the value but before splitting it.

for row in cursor: 
    unit = row[1] #get Unit in field list
    if unit is None:  continue  # continue to the next iteration in loop if None
JaredPilbeam2
MVP Regular Contributor

I solved my issue by accessing the last item in the list as opposed to the second.

This:

print(s[-1)#prints None elements too

Not this:

print(s[1])
0 Kudos