I'm a bit confused about what is going on in python here. I'm attempting to implement a very simple HashMap where the put method simply appends a tuple to an inner list associated with the hash table index. For some reason I'm unable to understand, python is appending the value to all inner lists. To see what I mean see the code here.
class HashTable:
def __init__(self, size=10):
self.table = [[]] * size
def __str__(self):
strList = []
for i in range(len(self.table)):
strList.append(str(self.table[i]))
return "".join(strList)
def put(self, key, value):
index = hash(key) % len(self.table)
self.table[index].append((key, value))
def get(self, key):
index = hash(key) % len(self.table)
for k, v in self.table[index]:
if k == key:
return v
return None
z = HashTable()
z.put("adam", "test")
print(z)
This code outputs:
[('adam', 'test')][('adam', 'test')][('adam', 'test')][('adam', 'test')][('adam', 'test')][('adam', 'test')][('adam', 'test')][('adam', 'test')][('adam', 'test')][('adam', 'test')]
Instead of what I would expect:
[][][][][][][][][('adam','test'][]
Does anyone have an idea of why a single append on an inner list would append the values to all lists inside self.table?
Thank you!