loop over list and modify in place

James Stroud jstroud at mbi.ucla.edu
Sat Sep 30 15:23:41 EDT 2006


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:

py> class B(object):
...   def __repr__(self):
...     return '<B>: %s' % self.value
...   def __init__(self):
...     self.value = None
...
py> alist = [B() for i in xrange(5)]
py> alist
[<B>: None, <B>: None, <B>: None, <B>: None, <B>: None]
py> [setattr(b,'value',v+5) for (v,b) in enumerate(alist)]
[None, None, None, None, None]
py> alist
[<B>: 5, <B>: 6, <B>: 7, <B>: 8, <B>: 9]
py> map(setattr, alist, ['value']*5, xrange(5))
[None, None, None, None, None]
py> alist
[<B>: 0, <B>: 1, <B>: 2, <B>: 3, <B>: 4]

-- 
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