List Comprehension Append Odds Twice Evens Once
You can do this in a single list comprehension with no outside tools. You just have to make and walk an inner sequence of values based on the value pulled from the outer sequence:
OtherNumList = [1, 2, 3, 8, 9]
OtherNumList2 = [rep for i in OtherNumList for rep in (i,)*(i%2+1)]
print(OtherNumList2)
The trick here is the second for
. It iterates a tuple
of one or two copies of i
, depending on whether i
is even (one copy) or odd (two copies). Conveniently, we don't even need a real boolean check here; (i%2+1)
is always 1
for even and 2
for odd already so we can use it to multiply directly. The resulting value is then produced the correct number of times directly, without additional flattening required.
One way could be by generating a nested list, and flattening it afterwards using for instance itertools.chain
. The tricky part is creating a flat list straight away, as you'll have to append more than one element at once when the the condition is not satisfied, so you need a little extra work to flatten the resulting list:
from itertools import chain
list(chain.from_iterable([i] if i%2 == 0 else [i]*2 for i in l))
Output
[1, 1, 2, 3, 3, 8, 9, 9]
Although it would seem to me that the optimal way to do this would be with a generator function, or very similarly, the one you've shared, but possibly preferable for large lists:
def my_fun(l):
for i in l:
if i%2 == 0:
yield i
else:
yield i
yield i
list(my_fun(l))
# [1, 1, 2, 3, 3, 8, 9, 9]