Reputation: 109
I have a list that looks like this
x = [ [ [[guy, 100], [guy, 200]],
[[guy, 50], [guy, 60]] ]
[ [[guy, 10], [guy, 20]],
[[guy, 5], [guy, 6]] ] ]
Each small list, is a guy, and the amount of time he has left before I delete him. I am trying to do it like this:
del x[0][0][0]
The error I keep getting is:
TypeError: List indices must be integers not lists.
I know what that error means, but I haven't found any great way of deleting that list. The only suggestions I've heard are
del x[0][0][0][:]
Which gives me the same error and:
x[0][0][0] = []
Which also gives me the same error.
The reality here is that this is a simplified version of my code. The 0's are actually loop variables in my real code.
Is the error that I am calling a list to identify the location of a list, or is it just that I'm deleting everything improperly?
Upvotes: 0
Views: 55
Reputation: 124
I'm not sure what caused your need for this style of "3-D" array like storage for your objects. You should be able to accomplish your task using a 1-D array and encapsulation of the time inside a class.
class guy:
def __init__(self, time):
self.timeBeforeDelete = time
def __str__(self):
return "{0}".format(self.timeBeforeDelete)
def printList(aList):
for item in aList:
print item
if __name__ == '__main__':
x = [guy(100), guy(200), guy(50), guy(60), guy(10), guy(20), guy(5), guy(6)]
printList(x)
del x[1]
printList(x)
This code allows you to delete freely from the list and keeps the complexity of the program to a minimum. Is there any specific reason that you are using the nested list structure that you are? To speak more to your error, you actually have a syntax error.
x = [ [ [[guy, 100], [guy, 200]],
[[guy, 50], [guy, 60]] ],
[ [[guy, 10], [guy, 20]],
[[guy, 5], [guy, 6]] ] ]
You were missing a comma to separate list items. This now works but this list structure really should be avoided since it makes accessing items in the list very cumbersome.
Upvotes: 0
Reputation: 31494
You missed a comma at the end of the second line. It should be:
x = [ [ [[guy, 100], [guy, 200]],
[[guy, 50], [guy, 60]] ],
[ [[guy, 10], [guy, 20]],
[[guy, 5], [guy, 6]] ] ]
In fact the error you say doesn't come from del
command but from the list definition.
You should also consider structuring your data in a better way.
Upvotes: 1