[Tutor] Best way to replace items in a list.
Jason Massey
jason.massey at gmail.com
Fri Oct 20 22:27:55 CEST 2006
You can access and change the elements in a list by directly referencing
their position in the list.
Something like:
>>> foo = [1,2,3]
>>> foo[0]
1
>>> foo[0] = 'a'
>>> foo
['a', 2, 3]
On 10/20/06, Chris Hengge <pyro9219 at gmail.com> wrote:
>
> Will that replace the location? or add to it?
>
> Thanks.
>
> On 10/20/06, Jason Massey <jason.massey at gmail.com > wrote:
> >
> > Why not:
> >
> > if item in list:
> > loc = list.index(item)
> > list[loc] = str
> >
> >
> >
> > On 10/20/06, Chris Hengge < pyro9219 at gmail.com> wrote:
> >
> > > I'm trying to build a little piece of code that replaces an item in a
> > > list.
> > >
> > > Here is a sample of what I'd like to do.
> > >
> > > str = "This was replaced"
> > >
> > > ff item in list:
> > > replace item with str
> > >
> > > I know I can do list.remove(item), but how do I place str back into
> > > that exact location?
> > >
> > > Is this how / best way?
> > >
> > > if item in list:
> > > loc = list.index(item)
> > > list.remove(item)
> > > list.insert(loc, str)
> > >
> > > Thanks.
> > >
> > > _______________________________________________
> > > Tutor maillist - Tutor at python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> > >
> > >
> >
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20061020/c4a4a6d5/attachment.html
More information about the Tutor
mailing list