Derek Xie Derek Xie - 2 months ago 6
Python Question

Using index on an empty list in python

For the following program, in the addEntry(self, dictKey, dictVal) function, I don't understand why the following line of code doesn't generate indexing error:

if hashBucket[i][0] == dictKey


self.buckets
is initially a list of empty list:
self.buckets = [[],[]...[]]


When addEntry is executed the first time,
hashBucket
is just an empty list, so I expect
hashBucket[i][0]
will generate an indexing error, but the program actually works, why? Thank you very much for your help.

Here is the program

class intDict(object):
"""A dictionary with integer keys"""

def __init__(self, numBuckets):
"""Create an empty dictionary"""
self.buckets = []
self.numBuckets = numBuckets
for i in range(numBuckets):
self.buckets.append([])

def addEntry(self, dictKey, dictVal):
"""Assumes dictKey an int. Adds an entry"""
hashBucket = self.buckets[dictKey%self.numBuckets]
for i in range(len(hashBucket)):
if hashBucket[i][0] == dictKey:
hashBucket[i] = (dictKey, dictVal)
return
hashBucket.append((dictKey, dictVal))

def getValue(self, dictKey):
"""Assumes dictKey an int. Returns entry associated with the key dictKey"""
hashBucket = self.buckets[dictKey%self.numBumBuckets]
for e in hashBucket:
if e[0] == dictKay:
return e[1]
return None

def __str__(self):
result = '{'
for b in self.buckets:
for e in b:
result = result + str(e[0]) + ":" + str(e[1]) + ','
return result[:-1] + '}' # result[:-1] omits the last coma

Answer

Since hashBucket is an empty list at first, for i in range(len(hashBucket)): is essentially for i in range(0):, meaning it never gets to the conditional if hashBucket[i][0] == dictKey on the first call to addEntry.

Comments