Derek Xie Derek Xie - 1 year ago 73
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

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

When addEntry is executed the first time,
is just an empty list, so I expect
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):

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)
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download