1

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!

S. Doe
  • 155
  • 1
  • 11

1 Answers1

0
class HashTable:
    def __init__(self, size=10):
        self.table = [[] for i in range(size)]

    def __str__(self):
        strList = []
        print(self.table)
        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)
        print(index)
        print(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 may help you

x=[[]]*10
x[0].append(10)
print(x)


y=[[] for i in range(10)]
y[0].append(10)
print(y)

enter image description here Observe that above code.While we are using the first method we are initailizing the same 2d arry for 10 times.So when you are appending the single 2d array multiples itself into 10 times(repeats).ie(same 2d array repeats 10 time)
In the second case we are creating 10 arrays inside an array so 10 different arrays inside an array.Thus we get the desired output

Naveenkumar M
  • 616
  • 3
  • 17