newbie question - python lists

Benjamin Kaplan benjamin.kaplan at case.edu
Fri Nov 6 18:07:17 CET 2009


On Fri, Nov 6, 2009 at 11:49 AM, lee <san82moon at gmail.com> wrote:
> On Nov 6, 7:48 pm, Jim <jim.heffe... at gmail.com> wrote:
>> On Nov 6, 9:15 am, lee <san82m... at gmail.com> wrote:
>>
>> > can anyone point wer am erroring.
>>
>> I'm not sure what you are trying to do, but it is odd, isn't it, that
>> you never refer to brain in the "for brain in brains:" loop?  I think
>> you are mixing i and brain somehow.
>>
>> Jim
>
> ok let me make it clear,
>
> brains = ['1','2']
> for brain in brains:
>    row['item'] = brain
>    items.append(row)
>    print items
>
> This produces
> [{'item': '1'}]
> [{'item': '2'}, {'item': '2'}]
> but i want
> [{'item': '1'}]
> [{'item': '1'}, {'item': '2'}]
>
> if i do items.append(brain), it gives,
> ['1', '2']
> but i want dictionary inside list.
> @Jon - Yes i want single item dict's
> @Robert - i use python 2.4 .
>
> Thanks
> Lee.

With Python, you're always dealing with objects, not with values. It
isn't apparent with immutable objects like strings and ints, but
here's what's actually happening. At the end, your list is [row, row].
It's the exact same dictionary. The value wasn't copied in. Try this

row = {}
row['item'] = 1

items = [row]
row['item'] = 2
print row

You get the same thing- you're changing the dict that's already in
items. In order to get two different elements, you have to use 2
different dicts.

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


> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list