Dictionary and List
Fredrik Lundh
fredrik at pythonware.com
Fri Oct 22 07:43:17 EDT 1999
sorot at my-deja.com wrote:
> I'm using python 1.5.1. While i'm writing the part of python script
> like this
>
> ## Part of script ##
> my_list = []
> my_dict = {'a':'','b':[]}
> x = ['a','b','c','d']
> for i in range(0,len(x)):
> my_dict['a'] = x[i]
> my_list.append(my_dict)
>
> print my_list
> ## end ##
>
> The out put should be like
> my_list = [{'a':'a','b':[]},{'a':'b','b':[]},{'a':'c','b':[]},
> {'a':'d','b':[]}]
nope. Python is all about references: since you're
using the *same* my_dict in all cases, the list will end
up with four references to my_dict. not four distinct
dictionaries.
to get distinct copies, move the my_dict assignment
inside the loop, or use the copy module.
</F>
<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->
More information about the Python-list
mailing list