List index out of range!!!

List index out of range!!!

danispag
Enthusiast Enthusiast
5,426 Views
2 Replies
Message 1 of 3

List index out of range!!!

danispag
Enthusiast
Enthusiast

I have a list of objects and I need to split the list evenly into chunks of 3. 

 

grpSel = cmds.ls(sl = True)

chunk_size = 3

chunks = [grpSel[i+i + chunk_size] for i in range(0, len(grpSel), chunk_size)]

 

I'm getting an error saying 'list index out of range'.

Image attached as a reference

How can I fix this?

 

Thanks in advance

 

0 Likes
Accepted solutions (1)
5,427 Views
2 Replies
Replies (2)
Message 2 of 3

jmreinhart
Advisor
Advisor
Accepted solution
import maya.cmds as cmds
grpSel = cmds.ls(sl = True)
chunk_size = 3
chunks = [grpSel[i:i + chunk_size] for i in range(0, len(grpSel), chunk_size)]

you've just got a little typo. on that bottom lines. To get a slice out of a list you write list_name[a:b]

0 Likes
Message 3 of 3

murphybeck
Community Visitor
Community Visitor

The way Python indexing works is that it starts at 0, so the first number of your list would be [0]. Index Error: List index out of range means you are trying to get an item in a list that doesn't exist. It means that you are referring to n-th element of the python list, while the length of the list is smaller than n. whenever you get this type of error please cross check with items that comes between/middle in range, and insure that their index is not last if you get output then you have made perfect error that mentioned.

 

An index in Python refers to a position within an ordered list . To retrieve an element of the list, you use the index operator ([]) . Using indexing you can easily get any element by its position.

0 Likes