[Tutor] Best way to replace items in a list.
Luke Paireepinart
rabidpoobear at gmail.com
Sat Oct 21 06:00:02 CEST 2006
Chris Hengge 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?
This is almost definitely not the best way to do that, though it depends
what results you're looking for.
This way will only replace the first occurrence of the item.
I don't know why you like the 'if item in ...' syntax so much ( ;) ),
but you could do this with a loop pretty easily.
#example
for index,item in enumerate(lst):
if item == 'Item To Replace':
lst[index] = 'Replaced!'
#--------
HTH,
-Luke
>
> 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
>
More information about the Tutor
mailing list