I tried to write a code that would add the position of a lists element to a new list. When I later on would try to add a new element to the original list from a different object, the placement of the object would be compared with the list where I saved my previous element to make sure it doesn’t get replaced.
I’ll paste the part of the code that is relevant to my question and it looks like this:
class gamefield:
def __init__(self):
self.table= [ [ "0" for i in range(10) ] for j in range(10) ]
class snake:
def __init__(self,sign):
self.sign = sign
self.x = random.randint(1,9)
self.y = random.randint(1,9)
self.bodylist = []
gamefield.table[self.x][self.y] = sign
self.bodylist.append(gamefield.table.index(sign))
field = gamefield()
snake1 = snake("+")
But I get the error:
“”self.bodylist.append(gamefield.table.index(sign))
ValueError: ‘+’ is not in list””
Shouldn’t the ‘+” be in the list since I add it to gamefield.table just before I execute the code that causes the error?
It’s not in the list
table, it’s in the listtable[x]. Your table is a list of lists, like so:You probably should add the tuple
(x,y)to the body list