newbie question - python lists
Brian Curtin
brian.curtin at gmail.com
Fri Nov 6 09:56:28 EST 2009
On Fri, Nov 6, 2009 at 08:15, lee <san82moon at gmail.com> wrote:
> hi,
>
> rfids= ['01','02']
> i = 01
> row = {}
> items = []
> for rfid in rfids:
>
> brains = ['1','2']
>
> if brains:
> for brain in brains:
> # this loop must run only once for each value of i
> row['itemnos'] = 'item_0'+str(i)+'s'
> print 'hi'
> items.append(row)
> print items
> break
> i=i+1
>
> the above code produces output a:
> [{'itemnos': 'item_02s'}, {'itemnos': 'item_02s'}]
> but i want it to be,
> [{'itemnos': 'item_01s'}, {'itemnos': 'item_02s'}]
>
> can anyone point wer am erroring.
> Thanks in advance.
>
Your call to items.append(row) passes row by reference. You added a row
dictionary with key "itemnos" set to value "item_01s" the first time through
the loop. The second time, you added a row dictionary with key "itemnos" set
to value "item_02s". This modified the underlying `row` dictionary, so it
also modified what you thought you put in the list in the first time through
the loop.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091106/91e690b8/attachment-0001.html>
More information about the Python-list
mailing list