Reputation: 303
I am using a line of code to iterate through a list of tuples and make the values inside them into integers. However, when I get to an element that is a NoneType, I get the following error.
TypeError: int() argument must be a string or a number, not 'NoneType'
I want to be able to iterate through the list of tuples and deal with NoneTypes. The NoneType needs to be left as None as it needs to be submitted to my database as None.
I think I may need to do some Try and Except code, but I am not sure where to begin.
The code I am using is as follows:
big_tuple = [('17', u'15', u'9', u'1'), ('17', u'14', u'1', u'1'), ('17', u'26', None, None)]
tuple_list = [tuple(int(el) for el in tup) for tup in big_tuple]
Without the last tuple, I would get the following returned:
[(17, 15, 9, 1), (17, 14, 1, 1)]
What I ideally want returned is:
[(17, 15, 9, 1), (17, 14, 1, 1), (17, 14, None, None)]
Any thoughts or suggestions would be really helpful.
Upvotes: 1
Views: 765
Reputation: 59664
This should work:
tuple_list = [
tuple(int(el) if el is not None else None for el in tup)
for tup in big_tuple
]
I mean check that the element is not None and only then convert it to int
, otherwise put None
.
Or you can make a separate function to convert the elements to make more readable and testable:
def to_int(el):
return int(el) if el is not None else None
tuple_list = [tuple(map(to_int, tup)) for tup in big_tuple]
Upvotes: 5