Python Index Out of Range

Working on a python node and I’m not understanding why I get an index out of range warning here.

“IndexError: index out of range: 45” the list is over 1000 strings long, whats going on?

# Enable Python support and load DesignScript library
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

# The inputs to this node will be stored as a list in the IN variables.
textContentInput = IN[0]

groupedText = 0

for i, tC in enumerate(textContentInput):
if tC != "":	
	if i + 1 > len(textContentInput):
		break
	else:			
		if tC[i + 1] != "":
			groupedText += 1
		else:
			"Do Nothing"
else:
	"Do Nothing"

# Assign your output to the OUT variable.
OUT = groupedText

Is your data nested? e.g. If the total number of strings is 1000, but it is divided into 45 separate lists, it would cause the above error.

It is not a nested list.

Here is a version of your script with the variables renamed, just so I can follow along a bit more easily:

strings = IN[0]
groupedText = 0
for i, string in enumerate(strings):
	if string != "":	
		if i + 1 > len(strings):
			break
		else:			
			if string[i + 1] != "":
				groupedText += 1

The first conditional tests if i + 1 is greater than the number of total strings in your list, which I don’t think will actually evaluate to true. For example, if you have a list of 10 objects, once the last object is reached, i will be equal to 9, making i + 1 equal to 10. Since this is already the last item in your list, i will never reach 11.

Next, we are accessing a certain character within the current string. When i = 0, the second character will be accessed and when i = 100 the 102nd character will be accessed. In your case, the loop is reaching the 43rd item, attempting to access the 45th character of that item and raising and IndexError. If I follow what you are trying to do, this line:

if tC[i + 1] != "":

should be replaced with this:

if textContentInput[i + 1] != "":

1 Like

Your right. Thank you. I’m still getting used to Python and I used enumerate just a bit ago and thought I was clever. I guess I don’t need the enumerate in there then since I’m not using the tC variable. I could do:

for i in range(len(textContentInput))

Correct?

EDIT: Just tested it out and the range(len( appears to work

Yes, in this case you can use that loop instead. For example:

for i in range(1, len(textContentInput)):
    if textContentInput[i] != "":
        groupedText += 1

Since you aren’t checking the first item in your list, you can start your range at 1.