loop over list and modify in place

James Stroud jstroud at mbi.ucla.edu
Sat Sep 30 17:28:22 EDT 2006


John Machin wrote:
> James Stroud wrote:
> 
>>Daniel Nogradi wrote:
>>
>>>Is looping over a list of objects and modifying (adding an attribute
>>>to) each item only possible like this?
>>>
>>>mylist = [ obj1, obj2, obj3 ]
>>>
>>>for i in xrange( len( mylist ) ):
>>>   mylist[i].newattribute = 'new value'
>>>
>>>
>>>I'm guessing there is a way to do this without introducing the (in
>>>principle unnecessary) index i, so what I'm really looking for is a
>>>looping method which doesn't pass references to the values of the
>>>items but to the items themselves.
>>
>>You can use map, or if you don't map, like list comprehension:
>>
> 
> 
> Call me crazy, but isn't the simple construct
>     for obj in mylist:
>         obj.newattribute = 'new value'
> what the OP was looking for?
> 

I thought he wanted a one liner.


-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list