Using index on an empty list in python
<p>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:</p>

<pre><code>if hashBucket[i][0] == dictKey
</code></pre>

<p><code>self.buckets</code> is initially a list of empty list:
<code>self.buckets = [[],[]...[]]</code><br>
When addEntry is executed the first time, <code>hashBucket</code> is just an empty list, so I expect <code>hashBucket[i][0]</code> will generate an indexing error, but the program actually works, why? Thank you very much for your help.</p>

<p>Here is the program</p>

<pre><code>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
</code></pre>

<p>when you try to loop over an empty list, nothing is going to happen, fire up a python interpeter and try this</p>

<pre><code>&gt;&gt;&gt; for i in range(len([])):
...     print(i)
... 
&gt;&gt;&gt;
</code></pre>

<p>Nothing gets printed, so in the same way if <code>hashBucket</code> is empty then everything inside the for loop will never get executed</p>

<pre><code>def addEntry(self, dictKey, dictVal):
    """Assumes dictKey an int. Adds an entry"""
    hashBucket = self.buckets[dictKey%self.numBuckets]
    for i in range(len(hashBucket)):
        # This is never executed if hashBucket is empty
        if hashBucket[i][0] == dictKey:
            hashBucket[i] = (dictKey, dictVal)
            return
    hashBucket.append((dictKey, dictVal))
</code></pre>

python list indexing hash