Hey guys so I was trying to implement a simple hash table in Python and was just curious about why this doesn't work so when I initialize my map variable I first use this.
class HashMap:
def __init__(self):
self.size = 10
self.map = [[] for _ in range(10)] #What to focus on
def getHash(self, key):
return key % self.size
def add(self,key, value):
#Get hashed bucket index
bucket = self.getHash(key)
self.map[bucket].append(value)
#To test my function.
h = HashMap()
h.add(1, "Swag")
print(h.map)
When I do this my hash-map works perfectly fine getting the desired result:
[[], ['Swag'], [], [], [], [], [], [], [], []]
However, when I do this:
self.map = [[]] * 10 #What to focus on
I then get this output:
[['Swag'], ['Swag'], ['Swag'], ['Swag'], ['Swag'], ['Swag'], ['Swag'], ['Swag'], ['Swag'], ['Swag']]
Does anyone know why this occurs? I'm a python newbie so anything would be nice Thanks!