Amine Saoudi
Amine Saoudi

Reputation: 1

List Comprehension returns none but I don't have anything that can result in none

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

expected result : [0, 2, 7, 0]

outcome : [None, None, None, None]

Upvotes: 0

Views: 428

Answers (1)

gboffi
gboffi

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

Related Questions