I have a function which has a for loop like this
def my_func():
order = [1,2,3,4,5,6,7]
my_list = []
for o in order:
tmp = is_odd(o)
if tmp:
my_list.append(tmp)
return my_list
def is_odd(n):
if n%2 != 0:
return n
else:
return False
I want to convert it into one line python for loop. I did it like this
def my_func():
order = [1,2,3,4,5,6,7]
my_list = [is_odd(o) for o in order if is_odd(o)]
return my_list
def is_odd(n):
if n%2 != 0:
return n
else:
return False
The problem with this code is that it call is_odd
function twice in each loop iteration. Is there any other way to convert loop into one line loop and calling is_odd
function only once?
(This is not original code. Just an example)