loop over list and modify in place

John Machin sjmachin at lexicon.net
Sat Sep 30 17:08:00 EDT 2006


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?




More information about the Python-list mailing list