I have a text files that I read to a list. This list contains integers and strings.
For example, my list could look like this:
[\"name\", \"test\", \"1\"
Try it, and catch the exception if it fails:
try:
return int(obj)
except ValueError:
...
Python takes the view of it's easier to ask for forgiveness than permission. Looking before you leap is often slower, harder to read, and can often introduce race conditions (not in this instance, but in general).
Also, modifying a list in-place like that is a bad idea, as accessing by index in Python is slow. Instead, consider using a list comprehension like this:
def intify(obj):
try:
return int(obj)
except ValueError:
return obj
mylist_with_ints = [intify(obj) for obj in mylist]
This makes a new list with the modified values and is more readable and efficient.
As a note, as we are just applying a function to every item of a list, map()
would also work well here:
mylist_with_ints = map(intify, mylist)
Note that if you need a list instead of an iterable in 3.x, you will want to wrap the map call in list()
.