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
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:
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