+ 1

How to have this code return None?

How to make the following code return none if the new_list remains empty? def largest_odd_times(L): """ Assumes L is a non-empty list of ints Returns the largest element of L that occurs an odd number of times in L. If no such element exists, returns None """ new_list = [] if True: for elm in L: if L.count(elm)%2!=0: new_list.append(elm) elif len(new_list) == 0: return None else: return max(new_list) print(largest_odd_times([3,9,5,3,5,3])) In case i call this function with list [2,2], it should return None instead of a ValueError. I refined this code to this: new_list = [] for elm in L: if L.count(elm)%2!=0: new_list.append(elm) else: continue return max(new_list)

4th Jul 2017, 10:57 AM
Chinmay Sharma
Chinmay Sharma - avatar
3 Answers
+ 3
add instead of the return if not new_list: return None return max(new_list) (Edited)
4th Jul 2017, 10:59 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 2
Sorry for the mistake ^^
4th Jul 2017, 11:10 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
This Works: new_list = [] for elm in L: if L.count(elm)%2!=0: new_list.append(elm) else: continue if not new_list: return None return max(new_list) Thank You
4th Jul 2017, 11:11 AM
Chinmay Sharma
Chinmay Sharma - avatar