newbie question - python lists

Emily Rodgers emily at
Fri Nov 6 18:00:30 CET 2009

"lee" <san82moon at> wrote in message 
news:8d1009a4-54c8-4bb3-9862-8b22e6b42a3b at
> 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.


As some others have pointed out, it is not totally clear from your code what 
you are trying to do, but I will forgive you for that because you are 
clearly not used to python!

I think what you are trying to do is:

items = []
rfids= ['01','02']
for rfid in rfids:
    items.append({'itemnos': 'item_%ss' % rfid})
print items

This can also be done using a list comprehension which is one of the (many) 
most useful features of python (imo):
rfids= ['01','02']
print [{'itemnos': 'item_%ss' % rfid} for rfid in rfids]

Or on one line (although it is always to be clearer rather trying to fit 
stuff into one line - it is not perl!)

print [{'itemnos': 'item_%ss' % rfid} for rfid in ['01', '02']]

Hope this helps.


More information about the Python-list mailing list