Reputation: 1
list_of_strings = ["a", "2", "7", "zebra"]
def safe_int(list):
try:
list[i] = int(list[i])
except ValueError:
list[i] = 0
new_list = [safe_int(list_of_strings) for i in range(len(list_of_strings))]
print new_list
Upvotes: 0
Views: 428
Reputation: 25023
Define your function so that it returns the result of the conversion or the number zero
def safe_int(l, i):
try:
return int(l[i])
except ValueError:
return 0
(note that I've passed explicitly i
to the function because the value of i
in the list comprehension is visible in the function due to a bad design decision in Python 2 that was corrected in Python 3) and then build the new_list
new_list = [ safe_int(list_of_strings, i) for ...]
I have to say that your approach is not idiomatic, I'd prefer to write
def safe_int(a_string):
try:
return int(a_string)
except ValueError:
return 0
new_list = [safe_int(s) for s in list_of_strings]
Upvotes: 1