[Tutor] Best way to replace items in a list.
Kent Johnson
kent37 at tds.net
Sat Oct 21 13:28:25 CEST 2006
Jason Massey wrote:
> Why not:
>
> if item in lst:
> loc = lst.index(item)
> lst[loc] = str
You can also just try to do the replacement and catch the ValueError
that is raised if the item is not there:
try:
loc = list.index(item)
list[loc] = str
except ValueError:
pass
If lst is long this will be faster because it only searches lst for item
once. If lst is short maybe the first version is better because the code
is shorter.
This is an example of two different approaches to handling exceptional
conditions: Look Before You Leap versus Easier to Ask Forgiveness than
Permission. In LBYL you check for the exceptional condition early, so
you avoid exceptions. In EAFP you proceed as if something is sure to
work and clean up after if you were wrong.
In many cases EAFP produces code that makes fewer assumptions about its
environment and is more suited to Python's dynamic style. In this simple
case it doesn't make any difference.
By the way don't use 'list' as the name of a variable (or 'file',
'dict', 'set' or 'str'), they are all the names of built-in types in
Python and using them as variable names will hide the built-in name.
Kent
More information about the Tutor
mailing list