I'm writing a Python class based on list. The constructor builds a list based on two other lists that are passed as parameters. The logic is roughly: copy list A to the new instance, then iterate over list B, adding some entries and using others to modify entries from list A.
I've got two versions of the constructor. In the first, list A and list B were processed by loops. Then I decided to get clever; I used a comprehension to replace the loop that adds list A to the new instance.
The first version of the constructor works perfectly. The second version returns an empty list, even though I can look at the value of self in the debugger immediately before the constructor ends, and see that it's correct.
Why is this happening, and what can I do to make the second version work?
Here is the code that makes the second version misbehave. It copies list A to the new instance, then iterates over the instance to update data in a dictionary that represents the items in list B. ba is list A; getkey is a function (passed as a parameter) which derives a dictionary key from a list element; _dictb is a dictionary that contains an element for each element in list B.
self = [ [bae,None] for bae in ba ] # Copy list A to self
for n in xrange(0,len(self)) : # Iterate over list B
_key = getkey( self[n][0])
if _dictb.has_key(_key) :
_dictb[_key] = n
In the first version, which works, the code above is replaced by this; the operations performed and the meanings of the variables are the same:
for bae in ba :
_key = getkey(bae)
if _dictb.has_key(_key) :
_dictb[_key] = len(self)
self.append( [bae,None] )