list.append not working?

Rex Turnbull rex at no_spam.dicad.de
Fri Jul 6 07:56:31 EDT 2007


Wildemar Wildenburger wrote:
> Abhishek Jain wrote:
>> with every iteration your previous values are overwritten ('md' is a 
>> dictionary) so thats why your are observing this ouput..
>>
>> check  if the following patch solves your problem
>>
>> for entity in temp:
>>             md['module']= entity.addr.get('module')
>>             md['id']=entity.addr.get('id')
>>             md['type']=entity.addr.get('type')
>>             #print md
>>             mbusentities.append(md)
>>             md = {}
>>             #print mbusentities
>>
>>
>> Regards
>> Abhi
> This will work, but may I suggest putting the md = {} line at the 
> *beginning* of the loop?
> I find seeing it at the end HIGHLY confusing. Declaring it in the 
> beginning makes sense, because you declare/initialize, then use it. But 
> using and *then* initializing it for the next iteration is kind of 
> quirky, because it breaks the logical encapsulation I would like to see 
> in *one* loop iteration.
> 
> /W

Hear, hear! to the declaration at the beginning.  Just went through a 
long bug search due to a similar behaviour.  Terrible.  I try to view 
the body of a loop as if it were a separate function/method.  If it 
makes sense from that point of view, it will make sense in 3 months. I 
mean, why would you want ot initialize something when you're done with it?

Cheers,
Rex



More information about the Python-list mailing list